package logic

import (
	"context"
	"errors"

	"juwan-backend/app/review/rpc/internal/models/reviews"
	"juwan-backend/app/review/rpc/internal/svc"
	"juwan-backend/app/review/rpc/pb"

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

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

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

func (l *SearchReviewsLogic) SearchReviews(in *pb.SearchReviewsReq) (*pb.SearchReviewsResp, 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.ReviewModelRO.Reviews.Query()

	if in.Id != nil {
		query = query.Where(reviews.IDEQ(in.GetId()))
	}
	if in.OrderId != nil {
		query = query.Where(reviews.OrderIDEQ(in.GetOrderId()))
	}
	if in.FromUserId != nil {
		query = query.Where(reviews.FromUserIDEQ(in.GetFromUserId()))
	}
	if in.ToUserId != nil {
		query = query.Where(reviews.ToUserIDEQ(in.GetToUserId()))
	}
	if in.Sealed != nil {
		query = query.Where(reviews.SealedEQ(in.GetSealed()))
	}

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

	out := make([]*pb.Reviews, len(list))
	for i, r := range list {
		out[i] = entReviewToPb(r)
	}

	return &pb.SearchReviewsResp{Reviews: out}, nil
}
