package logic

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

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

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

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

func (l *SearchPlayersLogic) SearchPlayers(in *pb.SearchPlayersReq) (*pb.SearchPlayersResp, error) {
	if in.Limit == nil || *in.Limit <= 0 {
		def := int64(20)
		in.Limit = &def
	}
	if *in.Limit > 100 {
		return nil, errors.New("limit too large")
	}
	if in.Offset == nil || *in.Offset < 0 {
		zero := int64(0)
		in.Offset = &zero
	}

	searcher := l.svcCtx.PlayerModelRO.Players.Query()

	if in.Gender != nil && *in.Gender != 0 {
		// 1 man  2 woman
		gender := true
		if *in.Gender == 2 {
			gender = false
		}
		searcher.Where(players.GenderEQ(gender))
	}
	all, err := searcher.Limit(int(*in.Limit)).Offset(int(*in.Offset)).All(l.ctx)
	if err != nil {
		logx.Errorf("SearchPlayers err: %v", err)
		return nil, errors.New("search players")
	}
	list := make([]*pb.Players, 0, len(all))
	for _, v := range all {
		temp := &pb.Players{}
		err := copier.Copy(temp, v)
		if err != nil {
			logx.Errorf("SearchPlayers copier.Copy err: %v", err)
			continue
		}
		list = append(list, temp)
	}

	return &pb.SearchPlayersResp{Players: list}, nil

}
