package logic

import (
	"context"
	"errors"

	"juwan-backend/app/community/rpc/internal/models/postlikes"
	"juwan-backend/app/community/rpc/internal/svc"
	"juwan-backend/app/community/rpc/pb"

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

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

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

func (l *SearchPostLikesLogic) SearchPostLikes(in *pb.SearchPostLikesReq) (*pb.SearchPostLikesResp, error) {
	limit := in.GetLimit()
	if limit <= 0 {
		limit = 20
	}
	if limit > 100 {
		return nil, errors.New("limit too large")
	}
	offset := in.GetOffset()
	if offset < 0 {
		offset = 0
	}

	query := l.svcCtx.CommunityModelRO.PostLikes.Query()
	if in.PostId != nil {
		query = query.Where(postlikes.PostIDEQ(in.GetPostId()))
	}
	if in.UserId != nil {
		query = query.Where(postlikes.UserIDEQ(in.GetUserId()))
	}

	list, err := query.
		Offset(int(offset)).
		Limit(int(limit)).
		All(l.ctx)
	if err != nil {
		logx.Errorf("searchPostLikes err: %v", err)
		return nil, errors.New("search post likes failed")
	}

	out := make([]*pb.PostLikes, len(list))
	for i, like := range list {
		out[i] = entPostLikeToPb(like)
	}

	return &pb.SearchPostLikesResp{PostLikes: out}, nil
}
