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

package player

import (
	"context"
	"encoding/json"
	"errors"
	"slices"
	"strconv"
	"time"

	"juwan-backend/app/player/api/internal/svc"
	"juwan-backend/app/player/api/internal/types"
	"juwan-backend/app/player/rpc/playerservice"
	"juwan-backend/app/users/rpc/usercenter"
	"juwan-backend/common/utils/contextj"

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

var ErrPlayerNotEligible = errors.New("player role not verified")

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

// 初始化当前用户的打手资料
func NewInitPlayerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InitPlayerLogic {
	return &InitPlayerLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InitPlayerLogic) InitPlayer(req *types.EmptyResp) (resp *types.PlayerProfile, err error) {
	userID, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}

	userResp, err := l.svcCtx.UserRpc.GetUsersById(l.ctx, &usercenter.GetUsersByIdReq{Id: userID})
	if err != nil {
		return nil, err
	}
	if userResp.GetUsers() == nil {
		return nil, ErrPlayerNotEligible
	}

	if !slices.Contains(userResp.GetUsers().VerifiedRoles, "player") {
		return nil, ErrPlayerNotEligible
	}

	verificationStatus := map[string]string{}
	if userResp.GetUsers().VerificationStatus != "" {
		_ = json.Unmarshal([]byte(userResp.GetUsers().VerificationStatus), &verificationStatus)
	}

	playerReq := &playerservice.SearchPlayersReq{UserId: &userID}
	playerResp, err := l.svcCtx.PlayerRpc.GetPlayerByUserId(l.ctx, playerReq)
	if err != nil {
		st, _ := status.FromError(err)
		if st.Code().String() != "NotFound" {
			logx.Errorf("InitPlayerLogic.GetPlayerByUserId err: %v", err)
			return nil, errors.New("get player failed")
		}

		_, err = l.svcCtx.PlayerRpc.AddPlayers(l.ctx, &playerservice.AddPlayersReq{
			UserId: userID,
			Status: "offline",
			Rating: 5,
			Gender: 1,
		})
		if err != nil {
			logx.Errorf("InitPlayerLogic.AddPlayers err: %v", err)
			return nil, errors.New("create player failed")
		}

		playerResp, err = l.svcCtx.PlayerRpc.GetPlayerByUserId(l.ctx, playerReq)
		if err != nil {
			logx.Errorf("InitPlayerLogic.GetPlayerByUserId after create err: %v", err)
			return nil, errors.New("get player failed")
		}
	}

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

	games := make([]string, 0, len(player.Games))
	for _, gameID := range player.Games {
		games = append(games, strconv.FormatInt(gameID, 10))
	}

	resp = &types.PlayerProfile{
		Id: player.Id,
		User: types.UserProfile{
			Id:            strconv.FormatInt(userResp.GetUsers().Id, 10),
			Username:      userResp.GetUsers().Username,
			Nickname:      userResp.GetUsers().Nickname,
			Avatar:        userResp.GetUsers().Avatar,
			Role:          userResp.GetUsers().CurrentRole,
			VerifiedRoles: append([]string{}, userResp.GetUsers().VerifiedRoles...),
			Phone:         userResp.GetUsers().Phone,
			Bio:           userResp.GetUsers().Bio,
			CreatedAt:     time.Unix(userResp.GetUsers().CreatedAt, 0).Format(time.DateTime),
		},
		Rating:      player.Rating,
		TotalOrders: player.TotalOrders,
		Status:      player.Status,
		Games:       games,
		Services:    []types.PlayerService{},
		Gender:      player.Gender,
		Tags:        append([]string{}, player.Tags...),
	}
	resp.User.VerificationStatus = verificationStatus
	if player.ShopId != 0 {
		resp.ShopId = strconv.FormatInt(player.ShopId, 10)
	}

	return resp, nil
}
