package logic

import (
	"context"
	"errors"

	"juwan-backend/app/community/rpc/internal/models/posts"
	"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 SearchPostsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *SearchPostsLogic) SearchPosts(in *pb.SearchPostsReq) (*pb.SearchPostsResp, 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.Posts.Query().
		Where(posts.DeletedAtIsNil())

	if in.GetId() > 0 {
		query = query.Where(posts.IDEQ(in.GetId()))
	}
	if in.AuthorId != nil {
		query = query.Where(posts.AuthorIDEQ(in.GetAuthorId()))
	}
	if in.AuthorRole != nil {
		query = query.Where(posts.AuthorRole(in.GetAuthorRole()))
	}
	if in.Title != nil {
		query = query.Where(posts.TitleContainsFold(in.GetTitle()))
	}
	if in.Content != nil {
		query = query.Where(posts.ContentContainsFold(in.GetContent()))
	}

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

	out := make([]*pb.Posts, len(list))
	for i, p := range list {
		out[i] = entPostToPb(p)
	}

	return &pb.SearchPostsResp{Posts: out}, nil
}
