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

// Distress: blacklist the current token (same as signout) but log it as a security event.
export const revokeHandler: Handler = async (ctx) => {
  const user = ctx.get('user') as { id: number; jti: string; exp: number; email?: string };
  const origin = ctx.get('origin') as string | undefined;

  console.warn(
    `[SECURITY] token revoked (distress) — user=${user.email || '?'}, origin=${origin || '-'}, ip=${clientIp(ctx)} — ${new Date().toISOString()}`,
  );

  await blacklistToken(user.jti, user.exp);

  // Distress wipes the vault session AND the stored protector key — forces a one-time master-password
  // re-setup, the correct "someone got in" behavior.
  clearVaultTokens(user.id).catch(() => {});
  clearVaultUnlockKey(user.id).catch(() => {});

  cleanupExpiredTokens().catch(() => {});

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