/**
 * GET  /api/secrets  — list all active secrets (names + scope + metadata only, never values)
 * POST /api/secrets  — create a new secret
 *
 * Audit rows are written for every mutation. Values never appear in any
 * response body or audit log — only name + scope are recorded.
 *
 * Both GET and POST require admin role.
 */

import { getDb, nowIso, newId } from '@/lib/db.js';
import { listSecrets, setSecret } from '@/lib/secrets.js';
import { requireSession } from '@/lib/auth.js';

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

function requireAdmin(session) {
  if (session.role !== 'admin' && session.role !== 'owner') {
    throw { status: 403, error: 'forbidden' };
  }
}

export async function GET(req) {
  try {
    const session = await requireSession(req);
    requireAdmin(session);
    return Response.json({ ok: true, secrets: listSecrets() });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    return Response.json({ ok: false, error: err.message }, { status: 500 });
  }
}

export async function POST(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return new Response('Invalid JSON', { status: 400 });
  }

  try {
    const session = await requireSession(req);
    requireAdmin(session);

    const name = String(body?.name || '').trim();
    const value = body?.value;
    const scope = String(body?.scope || 'global').trim();
    const source = String(body?.source || 'manual').trim();
    const metadata = body?.metadata || null;

    if (!name) return new Response('name is required', { status: 400 });
    if (!value && value !== 0) return new Response('value is required', { status: 400 });

    setSecret(name, String(value), { scope, source, metadata });

    // Audit row — value is never recorded.
    getDb().prepare(`
      INSERT INTO audit_logs (id, at, type, summary, status, meta)
      VALUES (?, ?, ?, ?, ?, ?)
    `).run(
      newId('audit'),
      nowIso(),
      'secrets.set',
      `Secret ${name} set (scope: ${scope})`,
      'ok',
      JSON.stringify({ name, scope, source })
    );

    return Response.json({ ok: true, name, scope });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    return Response.json({ ok: false, error: err.message }, { status: 500 });
  }
}
