/**
 * POST /api/privacy/verify — audit unlock attempt outcomes server-side.
 *
 * The client performs all cryptographic verification locally (Web Crypto API).
 * This route only records the audit trail for the outcome. No passphrase or
 * key material is ever sent to the server.
 *
 * Body:
 *   { success: boolean, attempt_count?: number, lockout_until?: string, project_id?: string }
 *
 * Audit types written per outcome:
 *   success  → privacy.unlock.success
 *   failure  → privacy.unlock.failure
 *   lockout  → privacy.unlock.lockout  (client also sets lockout_until in sessionStorage)
 *
 * RD-3 binding: this is the ONLY server route for privacy audit events.
 * There is no public POST /api/audit route.
 */

import { appendAudit } from '@/lib/runtime.js';
import { requireSession } from '@/lib/auth.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(req) {
  try {
    await requireSession(req);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ ok: false, error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }

  let body;
  try {
    body = await req.json();
  } catch {
    return Response.json({ ok: false, error: 'Invalid JSON' }, { status: 400 });
  }

  if (typeof body?.success !== 'boolean') {
    return Response.json({ ok: false, error: 'success must be a boolean' }, { status: 400 });
  }

  const { success, attempt_count, lockout_until, project_id } = body;

  try {
    let type, summary, meta;

    if (success) {
      type = 'privacy.unlock.success';
      summary = 'Privacy unlock succeeded';
      meta = { project_id: project_id || null };
    } else if (lockout_until) {
      type = 'privacy.unlock.lockout';
      summary = 'Privacy unlock locked out';
      meta = { project_id: project_id || null, lockout_until_iso: lockout_until };
    } else {
      const n = Number(attempt_count) || 1;
      type = 'privacy.unlock.failure';
      summary = `Privacy unlock failed (attempt ${n})`;
      meta = { project_id: project_id || null, attempt_count: n };
    }

    const row = appendAudit({ type, summary, status: 'complete', meta });

    return Response.json({ ok: true, id: row.id });
  } catch (err) {
    console.error('POST /api/privacy/verify error:', err);
    return Response.json({ ok: false, error: err.message }, { status: 500 });
  }
}
