package radar

import (
	"context"
	"fmt"
	"strings"

	usecase "apps/backend/internal/module/radar/usecase"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *ExploreOpportunitiesLogic) ExploreOpportunities(req *types.ExploreOpportunitiesReq) (*types.ExploreOpportunitiesData, error) {
	uid, err := ownerUID(l.ctx)
	if err != nil {
		return nil, err
	}
	brandID, productID := strings.TrimSpace(req.BrandId), strings.TrimSpace(req.ProductId)
	if (brandID == "") != (productID == "") {
		return nil, fmt.Errorf("brand_id and product_id must be provided together")
	}
	var res *usecase.ExploreResult
	if brandID != "" {
		res, err = l.svcCtx.Radar.ExploreProductOpportunities(l.ctx, uid, req.Terms, brandID, productID)
	} else {
		res, err = l.svcCtx.Radar.ExploreOpportunities(l.ctx, uid, req.Terms)
	}
	if err != nil {
		return nil, err
	}
	return &types.ExploreOpportunitiesData{
		SweepId:        res.SweepID,
		HitCount:       res.HitCount,
		JudgedCount:    res.JudgedCount,
		CreatedCount:   res.CreatedCount,
		MatchedCount:   res.MatchedCount,
		MergedCount:    res.MergedCount,
		TruncatedCount: res.TruncatedCount,
		CreditsUsed:    res.CreditsUsed,
	}, nil
}
