package usecase

import (
	"context"
	"fmt"
	"strings"

	"apps/backend/internal/module/radar/domain"
)

type ProductBrand struct {
	ID, DisplayName, TargetAudience string
	OwnerUID, UpdatedAt             int64
}

type ProductCatalogProduct struct {
	ID, BrandID, Label, ProductContext string
	PainPoints, MatchTags              []string
	ProviderCapabilityTerms            []string
	ProviderExcludeTerms               []string
	OwnerUID, UpdatedAt                int64
}

// ProductContextSource is deliberately read-only. Product CRUD remains owned
// by Scout; Radar only validates ownership and takes judgement-time snapshots.
type ProductContextSource interface {
	GetBrand(ctx context.Context, ownerUID int64, id string) (*ProductBrand, error)
	GetProduct(ctx context.Context, ownerUID int64, id string) (*ProductCatalogProduct, error)
}

type ProductContextSnapshot struct {
	BrandID, ProductID                            string
	BrandName, TargetAudience                     string
	ProductLabel, ProductContext                  string
	PainPoints, MatchTags                         []string
	ProviderCapabilityTerms, ProviderExcludeTerms []string
	BrandUpdatedAt, ProductUpdatedAt              int64
}

func (s *Service) LoadProductContext(ctx context.Context, ownerUID int64, brandID, productID string) (*ProductContextSnapshot, error) {
	if ownerUID <= 0 || strings.TrimSpace(brandID) == "" || strings.TrimSpace(productID) == "" {
		return nil, fmt.Errorf("%w: owner and paired brand/product IDs required", domain.ErrValidation)
	}
	if s.ProductSource == nil {
		return nil, fmt.Errorf("%w: product catalog unavailable", domain.ErrNotReady)
	}
	brand, err := s.ProductSource.GetBrand(ctx, ownerUID, brandID)
	if err != nil {
		return nil, err
	}
	product, err := s.ProductSource.GetProduct(ctx, ownerUID, productID)
	if err != nil {
		return nil, err
	}
	if brand == nil || product == nil {
		return nil, domain.ErrNotFound
	}
	if product.BrandID != brand.ID {
		return nil, domain.ErrValidation
	}
	return &ProductContextSnapshot{
		BrandID: brand.ID, ProductID: product.ID, BrandName: brand.DisplayName, TargetAudience: brand.TargetAudience,
		ProductLabel: product.Label, ProductContext: product.ProductContext,
		PainPoints: append([]string(nil), product.PainPoints...), MatchTags: append([]string(nil), product.MatchTags...),
		ProviderCapabilityTerms: append([]string(nil), product.ProviderCapabilityTerms...), ProviderExcludeTerms: append([]string(nil), product.ProviderExcludeTerms...),
		BrandUpdatedAt: brand.UpdatedAt, ProductUpdatedAt: product.UpdatedAt,
	}, nil
}
