/**
 * The three sites allowed to post a form to this API.
 *
 * The check is on `Origin`, which a browser sets itself and script cannot
 * forge — so it keeps our own forms working and everyone else's page out. It
 * is not a defence against a script with no browser attached; that is what the
 * Turnstile token and the per-IP limit are for, in that order.
 */

const FALLBACK_ORIGINS = [
  "https://elevaseo.com",
  "https://seoinsight.app",
  "https://seo.seoinsight.app",
];

/** Parsed once: ALLOWED_ORIGINS is a comma-separated list of exact origins. */
export function allowedOrigins(): string[] {
  const configured = process.env.ALLOWED_ORIGINS;
  if (!configured) return FALLBACK_ORIGINS;
  return configured
    .split(",")
    .map((entry) => entry.trim())
    .filter((entry) => entry !== "");
}

export function isAllowedOrigin(origin: string | null): origin is string {
  return origin !== null && allowedOrigins().includes(origin);
}

/** The host we record on the job, so a lead can be traced back to its site. */
export function siteFromOrigin(origin: string): string {
  try {
    return new URL(origin).host;
  } catch {
    return origin;
  }
}

/**
 * CORS for an allowed origin.
 *
 * `credentials` is on because the response carries the claim cookie, and a
 * cross-origin `Set-Cookie` is only honoured when the request was credentialed
 * — which also means `Access-Control-Allow-Origin` must echo the exact origin,
 * never `*`.
 */
export function corsHeaders(origin: string): Record<string, string> {
  return {
    "Access-Control-Allow-Origin": origin,
    "Access-Control-Allow-Credentials": "true",
    "Access-Control-Allow-Methods": "POST, GET, OPTIONS",
    "Access-Control-Allow-Headers": "content-type",
    Vary: "Origin",
  };
}
