package logic

import (
	"context"
	"errors"
	"juwan-backend/app/player/rpc/internal/models/playerservices"
	"juwan-backend/app/player/rpc/internal/svc"
	"juwan-backend/app/player/rpc/pb"
	"juwan-backend/app/snowflake/rpc/snowflake"

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

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

func NewAddPlayerServicesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddPlayerServicesLogic {
	return &AddPlayerServicesLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// -----------------------playerServices-----------------------
func (l *AddPlayerServicesLogic) AddPlayerServices(in *pb.AddPlayerServicesReq) (*pb.AddPlayerServicesResp, error) {
	idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
	if err != nil {
		logx.Errorf("addPlayerServices err:%v", err)
		return nil, errors.New("create player service id failed")
	}
	_, err = l.svcCtx.PlayerModelRW.PlayerServices.Create().
		SetID(idResp.Id).
		SetPlayerID(in.PlayerId).
		SetGameID(in.GameId).
		SetTitle(in.Title).
		SetDescription(in.Description).
		SetPrice(decimal.NewFromFloat(in.Price)).
		SetUnit(in.Unit).
		SetRankRange(in.RankRange).
		SetAvailability(in.Availability).
		SetRating(decimal.NewFromFloat(in.Rating)).
		SetIsActive(in.IsActive).
		Save(l.ctx)
	if err != nil {
		logx.Errorf("addPlayerServices err:%v", err)
		return nil, errors.New("add player service failed")
	}

	playerService, err := l.svcCtx.PlayerModelRO.PlayerServices.Query().Where(playerservices.IDEQ(idResp.Id)).First(l.ctx)
	if err != nil {
		logx.Errorf("getPlayerServicesById err:%v", err)
		return nil, errors.New("get player service failed")
	}

	pbPlayerService := pb.PlayerServices{
		Id:           playerService.ID,
		PlayerId:     playerService.PlayerID,
		GameId:       playerService.GameID,
		Title:        playerService.Title,
		Price:        playerService.Price.InexactFloat64(),
		Unit:         playerService.Unit,
		Availability: playerService.Availability,
		Rating:       playerService.Rating.InexactFloat64(),
		IsActive:     playerService.IsActive,
		CreatedAt:    playerService.CreatedAt.Unix(),
		UpdatedAt:    playerService.UpdatedAt.Unix(),
	}
	if playerService.Description != nil {
		pbPlayerService.Description = *playerService.Description
	}
	if playerService.RankRange != nil {
		pbPlayerService.RankRange = *playerService.RankRange
	}

	return &pb.AddPlayerServicesResp{PlayerServices: &pbPlayerService}, nil
}
