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

package player

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

	"juwan-backend/app/player/api/internal/svc"
	"juwan-backend/app/player/api/internal/types"
	"juwan-backend/app/player/rpc/pb"
	"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"
)

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

// 获取当前用户的打手资料
func NewGetMyPlayerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMyPlayerLogic {
	return &GetMyPlayerLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

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

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

	userResp, err := l.svcCtx.UserRpc.GetUsersById(l.ctx, &usercenter.GetUsersByIdReq{Id: userID})
	if err != nil {
		return nil, err
	}
	user := userResp.GetUsers()
	if user == nil {
		return nil, errors.New("user not found")
	}

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

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

	resp = &types.PlayerProfile{
		Id: player.Id,
		User: types.UserProfile{
			Id:                 strconv.FormatInt(user.Id, 10),
			Username:           user.Username,
			Nickname:           user.Nickname,
			Avatar:             user.Avatar,
			Role:               user.CurrentRole,
			VerifiedRoles:      append([]string{}, user.VerifiedRoles...),
			VerificationStatus: verificationStatus,
			Phone:              user.Phone,
			Bio:                user.Bio,
			CreatedAt:          time.Unix(user.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...),
	}
	if player.ShopId != 0 {
		resp.ShopId = strconv.FormatInt(player.ShopId, 10)
	}

	svcResp, svcErr := l.svcCtx.PlayerRpc.SearchPlayerServices(l.ctx, &pb.SearchPlayerServicesReq{
		PlayerId: player.Id,
		Limit:    100,
	})
	if svcErr != nil {
		logx.Errorf("GetMyPlayer SearchPlayerServices player=%d err: %v", player.Id, svcErr)
	} else {
		for _, s := range svcResp.PlayerServices {
			resp.Services = append(resp.Services, types.PlayerService{
				Id:           s.Id,
				PlayerId:     s.PlayerId,
				GameId:       s.GameId,
				Title:        s.Title,
				Description:  s.Description,
				Price:        s.Price,
				Unit:         s.Unit,
				RankRange:    s.RankRange,
				Availability: s.Availability,
			})
		}
	}

	return resp, nil
}
