// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package favorites

import (
	"context"
	"errors"

	"juwan-backend/app/search/api/internal/svc"
	"juwan-backend/app/search/api/internal/types"
	"juwan-backend/app/search/rpc/searchservice"
	"juwan-backend/common/utils/contextj"

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

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

// 检查收藏状态
func NewCheckFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckFavoriteLogic {
	return &CheckFavoriteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CheckFavoriteLogic) CheckFavorite(req *types.FavoriteCheckReq) (resp *types.FavoriteCheckResp, err error) {
	uid, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	if req.Id != uid {
		return nil, errors.New("user mismatch")
	}
	targetID, err := parseSnowflakeID(req.TargetId)
	if err != nil {
		return nil, err
	}

	out, err := l.svcCtx.SearchRpc.SearchFavorites(l.ctx, &searchservice.SearchFavoritesReq{
		Offset:     0,
		Limit:      1,
		UserId:     &uid,
		TargetType: &req.TargetType,
		TargetId:   &targetID,
	})
	if err != nil {
		return nil, err
	}

	return &types.FavoriteCheckResp{Favorited: len(out.GetFavorites()) > 0}, nil
}
