package logic

import (
	"context"
	"errors"

	"juwan-backend/app/search/rpc/internal/models/favorites"
	"juwan-backend/app/search/rpc/internal/svc"
	"juwan-backend/app/search/rpc/pb"

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

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

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

func (l *SearchFavoritesLogic) SearchFavorites(in *pb.SearchFavoritesReq) (*pb.SearchFavoritesResp, 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.SearchModelRO.Favorites.Query()
	if in.Id != nil {
		query = query.Where(favorites.IDEQ(in.GetId()))
	}
	if in.UserId != nil {
		query = query.Where(favorites.UserIDEQ(in.GetUserId()))
	}
	if in.TargetType != nil {
		query = query.Where(favorites.TargetTypeEQ(in.GetTargetType()))
	}
	if in.TargetId != nil {
		query = query.Where(favorites.TargetIDEQ(in.GetTargetId()))
	}

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

	out := make([]*pb.Favorites, len(list))
	for i, f := range list {
		out[i] = entFavoriteToPb(f)
	}

	return &pb.SearchFavoritesResp{Favorites: out}, nil
}
