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

package player

import (
	"context"
	"errors"
	"juwan-backend/app/player/rpc/playerservice"
	"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 CreateServiceLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 创建服务
func NewCreateServiceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateServiceLogic {
	return &CreateServiceLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateServiceLogic) CreateService(req *types.CreateServiceReq) (resp *types.PlayerService, 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 initialized")
		}
		logx.Errorf("failed to get player by user id: %v", err)
		return nil, errors.New("get player failed")
	}

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

	serviceResp, err := l.svcCtx.PlayerRpc.AddPlayerServices(l.ctx, &playerservice.AddPlayerServicesReq{
		PlayerId:     player.Id,
		GameId:       req.GameId,
		Title:        req.Title,
		Description:  req.Description,
		Price:        req.Price,
		Unit:         req.Unit,
		RankRange:    req.RankRange,
		Availability: req.Availability,
	})
	if err != nil {
		logx.Errorf("failed to create player service: %v", err)
		return nil, errors.New("failed to create player service")
	}

	service := serviceResp.GetPlayerServices()
	if service == nil {
		return nil, errors.New("failed to create player service")
	}

	return &types.PlayerService{
		Id:           service.Id,
		PlayerId:     service.PlayerId,
		GameId:       service.GameId,
		Title:        service.Title,
		Description:  service.Description,
		Price:        service.Price,
		Unit:         service.Unit,
		RankRange:    service.RankRange,
		Availability: service.Availability,
	}, nil
}
