package logic

import (
	"context"
	"errors"
	"juwan-backend/app/shop/rpc/internal/models/predicate"
	"juwan-backend/app/shop/rpc/internal/models/shopplayers"
	"juwan-backend/app/shop/rpc/internal/svc"
	"juwan-backend/app/shop/rpc/pb"
	"time"

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

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

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

func (l *SearchShopPlayersLogic) SearchShopPlayers(in *pb.SearchShopPlayersReq) (*pb.SearchShopPlayersResp, 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
	}

	preds := make([]predicate.ShopPlayers, 0, 8)
	if in.ShopId > 0 {
		preds = append(preds, shopplayers.ShopIDEQ(in.ShopId))
	}
	if in.PlayerId > 0 {
		preds = append(preds, shopplayers.PlayerIDEQ(in.PlayerId))
	}
	if in.IsPrimary {
		preds = append(preds, shopplayers.IsPrimaryEQ(true))
	}
	if in.JoinedAt > 0 {
		preds = append(preds, shopplayers.JoinedAtGTE(time.Unix(in.JoinedAt, 0)))
	}
	if in.LeftAt > 0 {
		preds = append(preds, shopplayers.LeftAtGTE(time.Unix(in.LeftAt, 0)))
	}

	query := l.svcCtx.ShopModelRO.ShopPlayers.Query()
	if len(preds) > 0 {
		query = query.Where(shopplayers.And(preds...))
	}

	list, err := query.
		Offset(int(in.Offset)).
		Limit(int(in.Limit)).
		All(l.ctx)
	if err != nil {
		logx.Errorf("search shop players failed, %s", err.Error())
		return nil, errors.New("search shop players failed")
	}

	result := make([]*pb.ShopPlayers, 0, len(list))
	for _, item := range list {
		pbItem := &pb.ShopPlayers{
			ShopId:    item.ShopID,
			PlayerId:  item.PlayerID,
			IsPrimary: item.IsPrimary,
			JoinedAt:  item.JoinedAt.Unix(),
		}
		if item.LeftAt != nil {
			pbItem.LeftAt = item.LeftAt.Unix()
		}
		result = append(result, pbItem)
	}

	return &pb.SearchShopPlayersResp{ShopPlayers: result}, nil
}
