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

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/playerservice"
	"juwan-backend/app/users/rpc/usercenter"

	"github.com/zeromicro/go-zero/core/logx"
)

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

// 获取打手详情
func NewGetPlayerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPlayerLogic {
	return &GetPlayerLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetPlayerLogic) GetPlayer(req *types.GetPlayerReq) (resp *types.PlayerProfile, err error) {
	playerResp, err := l.svcCtx.PlayerRpc.GetPlayersById(l.ctx, &playerservice.GetPlayersByIdReq{
		Id: req.Id,
	})
	if err != nil {
		logx.Errorf("GetPlayerLogic.GetPlayers err: %v", err)
		return nil, errors.New("failed to get player details")
	}
	player := playerResp.GetPlayers()
	if player == nil {
		return nil, errors.New("player not found")
	}
	completionRate := 0.0
	if player.TotalOrders > 0 {
		completionRate = float64(player.CompletedOrders) / float64(player.TotalOrders)
	}

	resp = &types.PlayerProfile{
		Id:             player.Id,
		Rating:         player.Rating,
		TotalOrders:    player.TotalOrders,
		CompletionRate: completionRate,
		Status:         player.Status,
		Gender:         player.Gender,
		Services:       []types.PlayerService{},
		Tags:           append([]string{}, player.Tags...),
	}

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

	if player.ShopId != 0 {
		resp.ShopId = strconv.FormatInt(player.ShopId, 10)
	}

	usersResp, err := l.svcCtx.UserRpc.GetUsersByIds(l.ctx, &usercenter.GetUsersByIdsReq{Ids: []int64{player.UserId}})
	if err != nil {
		return nil, err
	}
	if len(usersResp.Users) > 0 {
		u := usersResp.Users[0]
		verificationStatus := map[string]string{}
		if u.VerificationStatus != "" {
			_ = json.Unmarshal([]byte(u.VerificationStatus), &verificationStatus)
		}
		resp.User = types.UserProfile{
			Id:                 strconv.FormatInt(u.Id, 10),
			Username:           u.Username,
			Nickname:           u.Nickname,
			Avatar:             u.Avatar,
			Role:               u.CurrentRole,
			VerifiedRoles:      append([]string{}, u.VerifiedRoles...),
			VerificationStatus: verificationStatus,
			Phone:              u.Phone,
			Bio:                u.Bio,
			CreatedAt:          time.Unix(u.CreatedAt, 0).Format(time.DateTime),
		}
	}

	svcResp, svcErr := l.svcCtx.PlayerRpc.SearchPlayerServices(l.ctx, &playerservice.SearchPlayerServicesReq{
		PlayerId: player.Id,
		Limit:    100,
	})
	if svcErr != nil {
		logx.Errorf("GetPlayer 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
}
