import type { Handler } from 'hono';
import type { AuthIdentity } from '@@/auth-token';
import { blacklistToken, cleanupExpiredTokens, clearVaultTokens } from 'officerdb';

export const signoutHandler: Handler = async (ctx) => {
  const user = ctx.get('user') as AuthIdentity;

  // Only a session has something to blacklist. An API key cannot be signed out — it is revoked by id in
  // the keys API, which is the point of holding one instead of a session.
  if (user.jti && user.exp) await blacklistToken(user.jti, user.exp);

  // Drop the brokered vault session on logout (the protector key stays, so re-login is frictionless).
  clearVaultTokens(user.id).catch(() => {});

  // Opportunistic cleanup of expired tokens (non-blocking)
  cleanupExpiredTokens().catch(() => {});

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