// src/lib/keywords/import/brief-by-term-actions.ts — global (term-matched) YTG brief import.
"use server";
import * as wasm from "import-core";
import { importKeywordBriefAction } from "@/lib/keywords/actions";
import { keywordId as buildKeywordId } from "@/lib/keywords/import";
import { parseYtgTexts } from "@/lib/keywords/ytg-parse";
import { getSitesForActiveOrg } from "@/lib/sites/access";

/**
 * Import a YTG brief from the *global* Sources dropzone: parse the texts, derive
 * the target term (`brief.query`), slugify it with the SAME rule as the keyword
 * ETL/queries (`wasm.slugify`, via the `<siteId>-<slug>` id convention), and look
 * up that keyword on the active-org site.
 *
 * - Org guard: the `siteId` must be a site visible to the active org
 *   (`getSitesForActiveOrg` — owner/admin see all, member sees only granted). A
 *   foreign `siteId` throws (mirrors `getKeywordPromptBundle`).
 * - On match: attach the brief by reusing `importKeywordBriefAction` (the existing
 *   keyword-scoped attach/persist core — country-keyed JSONB merge). No divergent
 *   write path.
 * - On miss: no write; the UI shows the "Aucun mot-clé « term »…" guidance.
 *
 * `term` in the result is the parsed query (for that UI message), regardless of
 * match.
 */
export async function importBriefByTerm(
  siteId: string,
  briefText: string,
  guideText: string,
): Promise<{ matched: boolean; keywordId?: string; term: string }> {
  // Org guard: the site must be visible to the active org.
  const visibleSiteIds = new Set(
    (await getSitesForActiveOrg()).map((s) => s.id),
  );
  if (!visibleSiteIds.has(siteId)) {
    throw new Error("Site does not belong to the active organization");
  }

  const parsed = parseYtgTexts(
    [briefText, guideText],
    new Date().toISOString(),
  );
  if (!parsed.ok) {
    throw new Error(parsed.error);
  }

  const term = parsed.brief.query;
  const slug = wasm.slugify(term);
  // No usable term/slug → nothing to match against.
  if (!slug) return { matched: false, term };

  const id = buildKeywordId(siteId, slug);
  // Reuse the keyword-scoped attach/persist core. It re-asserts tenancy and
  // returns `{ ok:false, error:"Mot-clé introuvable." }` when no row matches.
  const result = await importKeywordBriefAction(siteId, id, [
    briefText,
    guideText,
  ]);
  if (!result.ok) {
    return { matched: false, term };
  }

  return { matched: true, keywordId: id, term };
}
