package radar

import (
	"context"

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

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

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

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

func (l *ImportOpportunitiesLogic) ImportOpportunities(req *types.ImportOpportunitiesReq) (*types.ImportOpportunitiesData, error) {
	uid, err := ownerUID(l.ctx)
	if err != nil {
		return nil, err
	}
	items := make([]usecase.ManualImportItem, 0, len(req.Items))
	for _, it := range req.Items {
		items = append(items, usecase.ManualImportItem{
			URL: it.Url, Text: it.Text, Author: it.Author, PostedAt: it.PostedAt,
		})
	}
	brandID, productID := req.BrandId, req.ProductId
	var results []usecase.ManualImportResult
	if brandID != "" || productID != "" {
		results, err = l.svcCtx.Radar.ImportManualProductOpportunities(l.ctx, uid, items, brandID, productID)
	} else {
		results, err = l.svcCtx.Radar.ImportManualOpportunities(l.ctx, uid, items)
	}
	if err != nil {
		return nil, err
	}
	out := make([]types.ImportedOpportunityResult, 0, len(results))
	for _, r := range results {
		out = append(out, types.ImportedOpportunityResult{
			Url: r.URL, OpportunityId: r.OpportunityID, Status: r.Status,
			IntentBand: r.IntentBand, IntentScore: r.IntentScore, Error: r.Error,
		})
	}
	return &types.ImportOpportunitiesData{Results: out}, nil
}
