import type { Handler } from 'hono';
import { blacklistToken, cleanupExpiredTokens } 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 { 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);
  cleanupExpiredTokens().catch(() => {});

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