package logic

import (
	"context"
	"errors"

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

	"entgo.io/ent/dialect/sql"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *SearchCommentsLogic) SearchComments(in *pb.SearchCommentsReq) (*pb.SearchCommentsResp, 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.Comments.Query().
		Where(comments.DeletedAtIsNil())

	if in.GetId() > 0 {
		query = query.Where(comments.IDEQ(in.GetId()))
	}
	if in.GetPostId() > 0 {
		query = query.Where(comments.PostIDEQ(in.GetPostId()))
	}
	if in.GetAuthorId() > 0 {
		query = query.Where(comments.AuthorIDEQ(in.GetAuthorId()))
	}
	if in.Content != nil {
		query = query.Where(comments.ContentContainsFold(in.GetContent()))
	}

	list, err := query.
		Order(comments.ByCreatedAt(sql.OrderAsc()), comments.ByID(sql.OrderAsc())).
		Offset(int(offset)).
		Limit(int(limit)).
		All(l.ctx)
	if err != nil {
		logx.Errorf("searchComments err: %v", err)
		return nil, errors.New("search comments failed")
	}

	out := make([]*pb.Comments, len(list))
	for i, c := range list {
		out[i] = entCommentToPb(c)
	}

	return &pb.SearchCommentsResp{Comments: out}, nil
}
