/**
 * POST /api/track
 * ───────────────
 * Lightweight client-side telemetry intake. Accepts
 *   { action, category?, brandId?, path?, metadata? }
 * and forwards it to trackEvent() so the admin Engagement +
 * Activity surfaces populate from real user navigation.
 *
 * Design notes:
 *   • Always returns 200 JSON — even for signed-out users or
 *     malformed payloads — so tracking failures never surface
 *     as user-facing errors or 4xx noise in the browser console.
 *   • category is validated against the PlatformEventCategory
 *     union; unknown categories fall back to "navigation" rather
 *     than crashing the typed insert.
 *   • action is truncated to 80 chars so a hostile/inflated
 *     client can't pollute the column with multi-KB payloads.
 *   • trackEvent() is fire-and-forget, so this handler returns
 *     in well under a millisecond.
 */
import { NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import {
  trackEvent,
  type PlatformEventCategory,
} from "@/lib/services/platform-telemetry";

export const dynamic = "force-dynamic";

const ALLOWED_CATEGORIES: readonly PlatformEventCategory[] = [
  "navigation",
  "search",
  "audit",
  "report",
  "integration",
  "content",
  "ai",
  "export",
  "settings",
  "auth",
  "admin",
  "seo",
  "technical",
];

function normalizeCategory(raw: unknown): PlatformEventCategory {
  return typeof raw === "string" &&
    (ALLOWED_CATEGORIES as readonly string[]).includes(raw)
    ? (raw as PlatformEventCategory)
    : "navigation";
}

export async function POST(req: Request) {
  const { userId } = await auth();
  // Signed-out hits are no-ops — we don't want to write anonymous
  // noise to PlatformEvent, and we don't want the client to treat
  // 401 as a failure and retry.
  if (!userId) return NextResponse.json({ ok: true });

  const body = (await req.json().catch(() => null)) as {
    action?: unknown;
    category?: unknown;
    brandId?: unknown;
    path?: unknown;
    metadata?: unknown;
  } | null;

  const action =
    typeof body?.action === "string" && body.action.trim()
      ? body.action.trim().slice(0, 80)
      : null;
  if (!action) return NextResponse.json({ ok: true });

  const category = normalizeCategory(body?.category);
  const brandId =
    typeof body?.brandId === "string" && body.brandId ? body.brandId : null;
  const path = typeof body?.path === "string" ? body.path : undefined;
  const metadata: Record<string, unknown> =
    body?.metadata && typeof body.metadata === "object" && !Array.isArray(body.metadata)
      ? (body.metadata as Record<string, unknown>)
      : {};

  trackEvent({
    userId,
    brandId,
    action,
    category,
    metadata: { ...metadata, ...(path ? { path } : {}) },
    request: req,
  });

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