/**
 * POST /api/site-tag/heatmap
 *
 * Ingest endpoint for click batches, scroll summaries and attention-zone
 * summaries emitted by the public/t.js heatmap module.
 */

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 HeatmapBody {
  siteId?: string;
  tagId?: string;
  visitorId?: string | null;
  sessionId?: string | null;
  pageUrl?: string;
  eventType?: string; // clicks | scroll | attention
  type?: string;       // alias — task spec uses "type"
  events?: unknown;
  maxScrollPercent?: number;
  milestonesReached?: unknown;
  timeOnPage?: number;
  sectionTimes?: unknown;
  pageWidth?: number;
  pageHeight?: number;
  viewportWidth?: number;
  viewportHeight?: number;
}

export async function POST(req: Request) {
  const cors = getCorsHeaders(req);
  let body: HeatmapBody;
  try {
    body = (await req.json()) as HeatmapBody;
  } 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 });
  }

  const eventType = body.eventType || body.type;
  if (!body.pageUrl || !eventType) {
    return NextResponse.json({ ok: false, error: "pageUrl and eventType required" }, { status: 400, headers: cors });
  }

  try {
    await prisma.heatmapEvent.create({
      data: {
        brandId: resolved.site.brandId,
        visitorId: body.visitorId ?? null,
        sessionId: body.sessionId ?? null,
        pageUrl: String(body.pageUrl).slice(0, 2048),
        eventType: String(eventType),
        events: (body.events as object) ?? undefined,
        maxScrollPercent: typeof body.maxScrollPercent === "number" ? Math.round(body.maxScrollPercent) : null,
        milestonesReached: (body.milestonesReached as object) ?? undefined,
        timeOnPage: typeof body.timeOnPage === "number" ? Math.round(body.timeOnPage) : null,
        sectionTimes: (body.sectionTimes as object) ?? undefined,
        pageWidth: typeof body.pageWidth === "number" ? Math.round(body.pageWidth) : null,
        pageHeight: typeof body.pageHeight === "number" ? Math.round(body.pageHeight) : null,
        viewportWidth: typeof body.viewportWidth === "number" ? Math.round(body.viewportWidth) : null,
        viewportHeight: typeof body.viewportHeight === "number" ? Math.round(body.viewportHeight) : null,
      },
    });
  } catch (err) {
    console.error("[site-tag/heatmap] write failed", err);
    return NextResponse.json({ ok: false, error: "Write failed" }, { status: 500, headers: cors });
  }

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