/**
 * GET /api/site-tag/script/:name
 *
 * Serves the Site Tag Intelligence modules from src/lib/site-tag/ as
 * plain JavaScript so public/t.js can load them at runtime. Keeps the
 * modules in TypeScript project tree (easy to lint/review/test) while
 * still reaching the browser.
 *
 * Only files on a whitelist are served — never arbitrary paths.
 */

import { NextResponse } from "next/server";
import { promises as fs } from "fs";
import path from "path";
import { getCorsHeaders } from "@/lib/services/page-lifecycle";

export const dynamic = "force-dynamic";

const ALLOWED = new Set(["attribution", "form-phone", "heatmap", "signals", "sms-detection"]);

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

export async function GET(
  req: Request,
  { params }: { params: { name: string } },
) {
  const cors = getCorsHeaders(req);
  const name = params.name.replace(/\.js$/, "");
  if (!ALLOWED.has(name)) {
    return NextResponse.json({ error: "Not found" }, { status: 404, headers: cors });
  }

  const filePath = path.join(process.cwd(), "src", "lib", "site-tag", `${name}.js`);
  try {
    const source = await fs.readFile(filePath, "utf8");
    return new NextResponse(source, {
      headers: {
        ...cors,
        "Content-Type": "application/javascript; charset=utf-8",
        // Short cache so CORS/credentials fixes roll out quickly. The modules
        // are small (a few KB each) and requested once per page load.
        "Cache-Control": "public, max-age=60, s-maxage=60, must-revalidate",
      },
    });
  } catch {
    return NextResponse.json({ error: "Not found" }, { status: 404, headers: cors });
  }
}
