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"

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

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

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

func (l *SearchPlayerServicesLogic) SearchPlayerServices(in *pb.SearchPlayerServicesReq) (*pb.SearchPlayerServicesResp, error) {
	if in.Limit <= 0 {
		in.Limit = 20
	}
	if in.Limit > 100 {
		return nil, errors.New("limit too large")
	}
	if in.Offset < 0 {
		in.Offset = 0
	}

	update := l.svcCtx.PlayerModelRO.PlayerServices.Query()
	if in.PlayerId != 0 {
		update.Where(playerservices.PlayerIDEQ(in.PlayerId))
	}

	all, err := update.
		Limit(int(in.Limit)).
		Offset(int(in.Offset)).
		All(l.ctx)
	if err != nil {
		return nil, errors.New("query all player services err")
	}

	list := make([]*pb.PlayerServices, 0, len(all))
	for _, v := range all {
		temp := &pb.PlayerServices{
			Id:           v.ID,
			PlayerId:     v.PlayerID,
			GameId:       v.GameID,
			Title:        v.Title,
			Price:        v.Price.InexactFloat64(),
			Unit:         v.Unit,
			Availability: v.Availability,
			Rating:       v.Rating.InexactFloat64(),
			IsActive:     v.IsActive,
			CreatedAt:    v.CreatedAt.Unix(),
			UpdatedAt:    v.UpdatedAt.Unix(),
		}
		if v.Description != nil {
			temp.Description = *v.Description
		}
		if v.RankRange != nil {
			temp.RankRange = *v.RankRange
		}
		list = append(list, temp)
	}

	return &pb.SearchPlayerServicesResp{PlayerServices: list}, nil
}
