// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2

package player

import (
	"context"
	"errors"
	"juwan-backend/app/player/rpc/pb"
	"juwan-backend/common/utils/contextj"

	"juwan-backend/app/player/api/internal/svc"
	"juwan-backend/app/player/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

type UpdatePlayerStatusLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 更新接单状态
func NewUpdatePlayerStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePlayerStatusLogic {
	return &UpdatePlayerStatusLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdatePlayerStatusLogic) UpdatePlayerStatus(req *types.UpdatePlayerStatusReq) (resp *types.EmptyResp, err error) {
	userId, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}

	playerResp, err := l.svcCtx.PlayerRpc.GetPlayerByUserId(l.ctx, &pb.SearchPlayersReq{UserId: &userId})
	if err != nil {
		st, _ := status.FromError(err)
		if st.Code().String() == "NotFound" {
			return nil, errors.New("player not initialized")
		}
		return nil, err
	}

	player := playerResp.GetPlayers()
	if player == nil {
		return nil, errors.New("player not initialized")
	}

	_, err = l.svcCtx.PlayerRpc.UpdatePlayers(l.ctx, &pb.UpdatePlayersReq{
		Id:     player.Id,
		Status: &req.Status,
	})
	if err != nil {
		return nil, err
	}

	return
}
