package logic

import (
	"context"
	"errors"

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

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

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

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

func (l *SearchCommentLikesLogic) SearchCommentLikes(in *pb.SearchCommentLikesReq) (*pb.SearchCommentLikesResp, 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.CommentLikes.Query()
	if in.GetCommentId() > 0 {
		query = query.Where(commentlikes.CommentIDEQ(in.GetCommentId()))
	}
	if in.GetUserId() > 0 {
		query = query.Where(commentlikes.UserIDEQ(in.GetUserId()))
	}

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

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

	return &pb.SearchCommentLikesResp{CommentLikes: out}, nil
}
