/**
 * POST /api/site-tag/rum
 *
 * Real User Monitoring ingest: Core Web Vitals (LCP, CLS, INP, TTFB)
 * plus device + connection hints. One row per page view (flushed by
 * public/t.js on beforeunload).
 */

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

export const dynamic = "force-dynamic";

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

interface RumBody {
  siteId?: string;
  tagId?: string;
  pageUrl?: string;
  lcp?: number | null;
  cls?: number | null;
  inp?: number | null;
  ttfb?: number | null;
  fcp?: number | null;
  device?: string | null;
  connection?: string | null;
  deviceMemory?: number | null;
  viewportW?: number | null;
  viewportH?: number | null;
}

function num(v: unknown): number | null {
  return typeof v === "number" && Number.isFinite(v) ? v : null;
}
function int(v: unknown): number | null {
  return typeof v === "number" && Number.isFinite(v) ? Math.round(v) : null;
}

export async function POST(req: Request) {
  const cors = getCorsHeaders(req);
  let body: RumBody;
  try {
    body = (await req.json()) as RumBody;
  } catch {
    return NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400, headers: cors });
  }

  const siteId = body.siteId || body.tagId;
  const resolved = await resolveSiteFromTag(siteId, body.pageUrl || "");
  if (!resolved.ok) {
    return NextResponse.json({ ok: false, error: resolved.error }, { status: resolved.status, headers: cors });
  }
  if (!body.pageUrl) {
    return NextResponse.json({ ok: false, error: "pageUrl required" }, { status: 400, headers: cors });
  }

  try {
    await prisma.realUserMetric.create({
      data: {
        brandId: resolved.site.brandId,
        pageUrl: String(body.pageUrl).slice(0, 2048),
        lcp: num(body.lcp),
        cls: num(body.cls),
        inp: num(body.inp),
        ttfb: num(body.ttfb),
        fcp: num(body.fcp),
        device: body.device ?? null,
        connection: body.connection ?? null,
        deviceMemory: num(body.deviceMemory),
        viewportW: int(body.viewportW),
        viewportH: int(body.viewportH),
      },
    });
  } catch (err) {
    console.error("[site-tag/rum] write failed", err);
    return NextResponse.json({ ok: false, error: "Write failed" }, { status: 500, headers: cors });
  }

  return NextResponse.json({ ok: true }, { headers: cors });
}
