// 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 RemoveFavoriteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 取消收藏
func NewRemoveFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RemoveFavoriteLogic {
	return &RemoveFavoriteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RemoveFavoriteLogic) RemoveFavorite(req *types.PathIDReq) (resp *types.EmptyResp, err error) {
	uid, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}

	current, err := l.svcCtx.SearchRpc.GetFavoritesById(l.ctx, &searchservice.GetFavoritesByIdReq{Id: req.Id})
	if err != nil {
		return nil, err
	}
	if current.GetFavorites() == nil || current.GetFavorites().GetUserId() != uid {
		return nil, errors.New("favorite not found")
	}

	_, err = l.svcCtx.SearchRpc.DelFavorites(l.ctx, &searchservice.DelFavoritesReq{Id: req.Id})
	if err != nil {
		return nil, err
	}

	return &types.EmptyResp{}, nil
}
