import { NextResponse } from "next/server";
import { logError } from "@/lib/error-log";
import { validateSession } from "@/lib/auth";

// Ingest endpoint for client-side error reports (from the error boundaries).
// Auth-optional: we attach the user/family if a session exists, but we never
// reject an error report for being unauthenticated — crashes can happen on
// public/logged-out screens too.
export async function POST(request: Request) {
  try {
    const body = await request.json().catch(() => ({}));
    const { message, stack, url, digest, level, metadata } = body as {
      message?: string;
      stack?: string;
      url?: string;
      digest?: string;
      level?: "error" | "warn" | "fatal";
      metadata?: Record<string, unknown>;
    };

    if (!message || typeof message !== "string") {
      return NextResponse.json({ error: "message required" }, { status: 400 });
    }

    let userId: string | null = null;
    let familyId: string | null = null;
    try {
      const auth = await validateSession();
      userId = auth.session?.userId ?? null;
      familyId = auth.session?.familyId ?? null;
    } catch {
      // best-effort only
    }

    await logError({
      source: "client",
      level: level === "warn" || level === "fatal" ? level : "error",
      message,
      stack,
      url,
      digest,
      userId,
      familyId,
      userAgent: request.headers.get("user-agent"),
      metadata: metadata && typeof metadata === "object" ? metadata : {},
    });

    return NextResponse.json({ ok: true });
  } catch {
    // Swallow — the reporter must never surface its own error to the user.
    return NextResponse.json({ ok: false });
  }
}
