package logic

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

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

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

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

func (l *SearchShopInvitationsLogic) SearchShopInvitations(in *pb.SearchShopInvitationsReq) (*pb.SearchShopInvitationsResp, 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.ShopInvitations, 0, 8)
	if in.Id > 0 {
		preds = append(preds, shopinvitations.IDEQ(in.Id))
	}
	if in.ShopId > 0 {
		preds = append(preds, shopinvitations.ShopIDEQ(in.ShopId))
	}
	if in.PlayerId > 0 {
		preds = append(preds, shopinvitations.PlayerIDEQ(in.PlayerId))
	}
	if in.Status != "" {
		preds = append(preds, shopinvitations.StatusEQ(in.Status))
	}
	if in.InvitedBy > 0 {
		preds = append(preds, shopinvitations.InvitedByEQ(in.InvitedBy))
	}
	if in.CreatedAt > 0 {
		preds = append(preds, shopinvitations.CreatedAtGTE(time.Unix(in.CreatedAt, 0)))
	}
	if in.RespondedAt > 0 {
		preds = append(preds, shopinvitations.RespondedAtGTE(time.Unix(in.RespondedAt, 0)))
	}

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

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

	result := make([]*pb.ShopInvitations, 0, len(list))
	for _, item := range list {
		pbItem := &pb.ShopInvitations{
			Id:        item.ID,
			ShopId:    item.ShopID,
			PlayerId:  item.PlayerID,
			Status:    item.Status,
			InvitedBy: item.InvitedBy,
			CreatedAt: item.CreatedAt.Unix(),
		}
		if item.RespondedAt != nil {
			pbItem.RespondedAt = item.RespondedAt.Unix()
		}
		result = append(result, pbItem)
	}

	return &pb.SearchShopInvitationsResp{ShopInvitations: result}, nil
}
