/**
 * GET /api/site-tag/competitors?site_id=ms_xxx
 * --------------------------------------------------
 * Returns the brand's competitor domain list for the Site Tag to
 * cross-reference against outbound-click destinations and document
 * referrers. Feeds three t.js events:
 *   • competitor_visit     — outbound click lands on a known
 *                            competitor domain
 *   • competitor_referral  — the landing visitor's referrer is a
 *                            known competitor domain
 *   • competitive_journey  — session starts from a competitor, ends
 *                            at a competitor (revealing which pages
 *                            visitors compare before picking us
 *                            or leaving)
 *
 * Public endpoint — matches the security model of /api/collect. The
 * site_id is already publicly visible on the customer's website, so
 * restricting the response by origin would force a proper request
 * from every embed surface without buying much — the competitor list
 * is business-intel rather than a secret. Response is capped at 200
 * entries and the list is cached 1h in sessionStorage client-side
 * so this route is at most one request per visitor per hour.
 *
 * Response shape:
 *   { ok: true, competitors: [{ domain: "example.com", name: "Example Inc." }] }
 *
 * Empty list on any error path — the Site Tag treats
 * "competitors list unavailable" and "no competitors configured"
 * identically. 200 is always returned so the browser doesn't
 * surface a console error on customer pages.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getCorsHeaders } from "@/lib/services/page-lifecycle";

export const dynamic = "force-dynamic";

// Short-cache the response on CDN + browser — competitor lists
// change on the order of days / weeks, not seconds. 10m covers
// most editing latency without forcing a fetch on every page.
const CACHE_HEADERS = {
  "Cache-Control": "public, max-age=600, stale-while-revalidate=3600",
};

export async function OPTIONS(req: Request) {
  return new NextResponse(null, { status: 204, headers: getCorsHeaders(req) });
}

function emptyResponse(req: Request) {
  return NextResponse.json(
    { ok: true, competitors: [] },
    { status: 200, headers: { ...getCorsHeaders(req), ...CACHE_HEADERS } },
  );
}

export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url);
    const siteId = searchParams.get("site_id");
    if (!siteId || !siteId.startsWith("ms_")) return emptyResponse(req);

    const site = await prisma.trackedSite
      .findUnique({
        where: { siteId },
        select: { id: true, brandId: true, status: true },
      })
      .catch(() => null);
    if (!site || site.status !== "active") return emptyResponse(req);

    const competitors = await prisma.competitor
      .findMany({
        where: { brandId: site.brandId, isActive: true },
        select: { domain: true, name: true },
        take: 200,
      })
      .catch(() => [] as Array<{ domain: string; name: string }>);

    // Normalise domains — lower-case + leading-www stripped so the
    // client's comparison (also normalised) matches reliably.
    const normalised = competitors
      .map((c) => ({
        domain: (c.domain || "").trim().toLowerCase().replace(/^www\./, ""),
        name: c.name || null,
      }))
      .filter((c) => c.domain.length > 0);

    return NextResponse.json(
      { ok: true, competitors: normalised },
      { status: 200, headers: { ...getCorsHeaders(req), ...CACHE_HEADERS } },
    );
  } catch {
    return emptyResponse(req);
  }
}
