import type { BrandProduct } from "../domain/types";

/** 掃描關鍵字池：產品痛點 + tags（可多產品合併） */
export function buildScanKeywordPool(
  products: BrandProduct | BrandProduct[] | null | undefined,
): string[] {
  const list = !products ? [] : Array.isArray(products) ? products : [products];
  const pool = list.flatMap((product) => [
    ...(product.match_tags || []),
    ...(product.pain_points || []),
    product.label || "",
  ])
    .map((k) => k.trim())
    .filter(Boolean);
  return [...new Set(pool)];
}

export function scoreProductForPost(
  product: BrandProduct,
  searchTag: string,
  postText: string,
): number {
  const tags = [...product.match_tags, ...product.pain_points, product.label].filter(Boolean);
  const hay = `${searchTag} ${postText}`.toLowerCase();
  let hits = 0;
  for (const tag of tags) {
    const t = tag.toLowerCase();
    if (t && hay.includes(t)) hits += 1;
  }
  if (!hits) return 0;
  // 0–100
  return Math.min(99, 40 + hits * 18);
}

export function resolveProductForPost(opts: {
  products: BrandProduct[];
  preferredProductId?: string | null;
  searchTag: string;
  postText: string;
}): { product: BrandProduct | null; score: number } {
  const { products, preferredProductId, searchTag, postText } = opts;
  if (!products.length) return { product: null, score: 0 };

  let best: BrandProduct | null = null;
  let bestScore = 0;
  for (const p of products) {
    const s = scoreProductForPost(p, searchTag, postText);
    if (s > bestScore) {
      bestScore = s;
      best = p;
    }
  }
  if (best && bestScore >= 40) return { product: best, score: bestScore };

  if (preferredProductId) {
    const pref = products.find((p) => p.id === preferredProductId);
    if (pref) return { product: pref, score: Math.max(bestScore, 35) };
  }
  return { product: products[0] || null, score: bestScore || 30 };
}

export function opportunityLine(product: BrandProduct | null, searchTag: string): string {
  if (!product) return `關鍵字「${searchTag}」命中；尚未對上產品線`;
  const pain = product.pain_points[0] || product.match_tags[0] || product.label;
  return `對上「${product.label}」· 痛點／語境：${pain}`;
}
