package logic

import (
	"context"
	"errors"

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

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

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

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

func (l *AddFavoritesLogic) AddFavorites(in *pb.AddFavoritesReq) (*pb.AddFavoritesResp, error) {
	if in.GetUserId() <= 0 {
		return nil, errors.New("userId is required")
	}
	if !validTargetType(in.GetTargetType()) {
		return nil, errors.New("invalid targetType")
	}
	if in.GetTargetId() <= 0 {
		return nil, errors.New("targetId is required")
	}

	idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
	if err != nil {
		return nil, errors.New("create favorite id failed")
	}

	created, err := l.svcCtx.SearchModelRW.Favorites.Create().
		SetID(idResp.Id).
		SetUserID(in.GetUserId()).
		SetTargetType(in.GetTargetType()).
		SetTargetID(in.GetTargetId()).
		Save(l.ctx)
	if err != nil {
		if models.IsConstraintError(err) {
			existing, getErr := l.svcCtx.SearchModelRW.Favorites.Query().
				Where(
					favorites.UserIDEQ(in.GetUserId()),
					favorites.TargetTypeEQ(in.GetTargetType()),
					favorites.TargetIDEQ(in.GetTargetId()),
				).
				Only(l.ctx)
			if getErr == nil {
				return &pb.AddFavoritesResp{Id: existing.ID}, nil
			}
		}
		logx.Errorf("addFavorites err: %v", err)
		return nil, errors.New("add favorite failed")
	}

	return &pb.AddFavoritesResp{Id: created.ID}, nil
}
