/**
 * GET    /api/privacy/config  — return whether a passphrase is configured
 * POST   /api/privacy/config  — create or replace the passphrase configuration
 * DELETE /api/privacy/config  — reset passphrase and clear all artifact protections
 */

import { getDb, nowIso, newId } from '@/lib/db.js';
import { appendAudit } from '@/lib/runtime.js';
import { requireSession } from '@/lib/auth.js';

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

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

  try {
    const db = getDb();
    const row = db.prepare('SELECT * FROM privacy_config ORDER BY updated_at DESC LIMIT 1').get();
    if (!row) {
      return Response.json({ configured: false });
    }
    return Response.json({
      configured: true,
      kdf: row.kdf,
      iterations: row.iterations,
      salt_b64: row.salt_b64,
      hmac_b64: row.hmac_b64,
      idle_timeout_ms: row.idle_timeout_ms,
    });
  } catch (err) {
    console.error('GET /api/privacy/config error:', err);
    return Response.json({ ok: false, error: err.message }, { status: 500 });
  }
}

export async function POST(req) {
  try {
    await requireSession(req);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ 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 });
  }

  const kdf = String(body?.kdf || '').trim();
  const iterations = body?.iterations;
  const salt_b64 = String(body?.salt_b64 || '').trim();
  const hmac_b64 = String(body?.hmac_b64 || '').trim();
  const idle_timeout_ms = body?.idle_timeout_ms !== undefined
    ? Number(body.idle_timeout_ms)
    : 900000;
  const is_change = Boolean(body?.is_change);

  if (!kdf) return Response.json({ ok: false, error: 'kdf is required' }, { status: 400 });
  if (!Number.isInteger(iterations) || iterations < 100000) {
    return Response.json({ ok: false, error: 'iterations must be an integer >= 100000' }, { status: 400 });
  }
  if (!salt_b64) return Response.json({ ok: false, error: 'salt_b64 is required' }, { status: 400 });
  if (!hmac_b64) return Response.json({ ok: false, error: 'hmac_b64 is required' }, { status: 400 });

  try {
    const db = getDb();

    // Check if there was a previous config (for audit type)
    const existing = db.prepare('SELECT id FROM privacy_config LIMIT 1').get();
    const was_configured = Boolean(existing);

    // Upsert: delete existing rows, then insert a fresh row
    db.prepare('DELETE FROM privacy_config').run();
    const id = newId('pvc');
    const now = nowIso();
    db.prepare(`
      INSERT INTO privacy_config (id, kdf, iterations, salt_b64, hmac_b64, idle_timeout_ms, created_at, updated_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `).run(id, kdf, iterations, salt_b64, hmac_b64, idle_timeout_ms, now, now);

    const auditType = (is_change || was_configured)
      ? 'privacy.passphrase.changed'
      : 'privacy.passphrase.set';
    const summary = (is_change || was_configured)
      ? 'Privacy passphrase changed'
      : 'Privacy passphrase set';
    appendAudit({
      type: auditType,
      summary,
      status: 'complete',
      meta: { kdf, iterations, was_configured },
    });

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

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

  try {
    const db = getDb();

    // Execute in a transaction: clear config + unprotect all artifacts + audit row.
    // The audit write is inside the transaction so it is committed atomically (P0-4).
    let artifacts_cleared = 0;
    try {
      db.exec('BEGIN');
      db.prepare('DELETE FROM privacy_config').run();
      const result = db.prepare('UPDATE artifacts SET is_protected = 0 WHERE is_protected = 1').run();
      artifacts_cleared = result.changes;
      // Audit row inside transaction — committed atomically with the data delete.
      appendAudit({
        type: 'privacy.passphrase.reset',
        summary: 'Privacy passphrase reset — all protections cleared',
        status: 'complete',
        meta: { artifacts_cleared },
      });
      db.exec('COMMIT');
    } catch (txErr) {
      try { db.exec('ROLLBACK'); } catch {}
      throw txErr;
    }

    return Response.json({ ok: true, artifacts_cleared });
  } catch (err) {
    console.error('DELETE /api/privacy/config error:', err);
    return Response.json({ ok: false, error: err.message }, { status: 500 });
  }
}
