import type { Handler } from 'hono';
import { clearVaultTokens, clearVaultUnlockKey } from 'officerdb';
import { triggerLockdown } from './panic';
import { clientIp } from './client-ip';

// Trigger the panic lockdown. Authenticated (Bearer token) — no password in the body. Once tripped,
// all logins and existing sessions are refused until the server is manually restarted.
export const panicHandler: Handler = async (ctx) => {
  const user = ctx.get('user') as { id?: number; email?: string } | undefined;
  const origin = ctx.get('origin') as string | undefined;
  triggerLockdown(`/panic (user=${user?.email || '?'}, origin=${origin || '-'}, ip=${clientIp(ctx)})`);

  // Panic wipes the vault session AND the protector key (like distress).
  if (user?.id) {
    clearVaultTokens(user.id).catch(() => {});
    clearVaultUnlockKey(user.id).catch(() => {});
  }

  return ctx.json({ ok: true });
};
