// src/components/keywords/enrich-status-logic.ts — logique PURE de la pastille
// de statut d'enrichissement (server/react-free). Isolée de la cellule (qui
// importe lucide/tooltip, non chargeables sous `--conditions=react-server`)
// pour rester testable en isolation.
import type { KeywordEnrichment, KeywordSource } from "@/lib/keywords/types";

/** Libellés courts par source (tooltip). */
export const SOURCE_LABEL: Record<KeywordSource, string> = {
  mangools: "Mangools",
  seranking: "SE-Ranking",
  semrush: "Semrush",
  ahrefs: "Ahrefs",
  gsc: "GSC",
  manual: "Manuel",
};

/** Messages FR courts par code d'erreur du rail (worker analytics). */
const ERROR_LABEL: Record<string, string> = {
  quota: "quota atteint",
  token: "token invalide",
  not_found: "aucune donnée",
  internal: "erreur interne",
  no_location: "pays non couvert",
};

function errorLabel(code: string | undefined): string {
  return (code && ERROR_LABEL[code]) ?? "échec";
}

export type Display =
  | { kind: "active" }
  | { kind: "error"; errors: { source: KeywordSource; label: string }[] }
  | { kind: "none" };

/** Pur, testable : réduit un enrichissement multi-sources à ce qu'il faut
 *  afficher. Priorité : un enrichissement en vol (spinner) prime sur une erreur,
 *  qui prime sur rien. */
export function deriveDisplay(
  enrichment: KeywordEnrichment | undefined,
): Display {
  if (!enrichment) return { kind: "none" };
  const errors: { source: KeywordSource; label: string }[] = [];
  for (const [source, state] of Object.entries(enrichment) as [
    KeywordSource,
    KeywordEnrichment[KeywordSource],
  ][]) {
    if (!state) continue;
    if (state.status === "queued" || state.status === "syncing") {
      return { kind: "active" };
    }
    if (state.status === "error") {
      errors.push({ source, label: errorLabel(state.error) });
    }
  }
  return errors.length > 0 ? { kind: "error", errors } : { kind: "none" };
}
