/**
 * PATCH  /api/secrets/[name]  — rotate secret to a new value
 * DELETE /api/secrets/[name]  — revoke a secret
 *
 * Both write audit_logs rows. Values never appear in audit rows or responses.
 * Scope can be passed as a query param: ?scope=global or ?scope=agent:<id>
 * Both operations require admin role.
 */

import { getDb, nowIso, newId } from '@/lib/db.js';
import { rotateSecret, deleteSecret } 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' };
  }
}

function writeAudit(action, name, scope) {
  getDb().prepare(`
    INSERT INTO audit_logs (id, at, type, summary, status, meta)
    VALUES (?, ?, ?, ?, ?, ?)
  `).run(
    newId('audit'),
    nowIso(),
    `secrets.${action}`,
    `Secret ${name} ${action === 'rotate' ? 'rotated' : 'deleted'} (scope: ${scope})`,
    'ok',
    JSON.stringify({ name, scope, action })
  );
}

export async function PATCH(req, { params }) {
  const name = (await params).name;

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

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

    const value = body?.value;
    const scope = String(body?.scope || new URL(req.url).searchParams.get('scope') || 'global').trim();

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

    rotateSecret(name, String(value), { scope });
    writeAudit('rotate', name, scope);
    return Response.json({ ok: true, name, scope, rotated: true });
  } 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: err.message.includes('not found') ? 404 : 500 });
  }
}

export async function DELETE(req, { params }) {
  const name = (await params).name;

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

    const scope = String(new URL(req.url).searchParams.get('scope') || 'global').trim();
    deleteSecret(name, { scope });
    writeAudit('delete', name, scope);
    return Response.json({ ok: true, name, scope, deleted: true });
  } 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: err.message.includes('not found') ? 404 : 500 });
  }
}
