import { createRouter } from '../../create-router';
import {
  authAudit,
  originMiddleware,
  userMiddleware,
  bodyParser,
  signinRateLimiter,
  signupRateLimiter,
  forgotPasswordRateLimiter,
} from '../../_middlewares';
import { signinHandler } from './signin';
import { signoutHandler } from './signout';
import { verifyTokenHandler } from './verify-token';
import { changePasswordHandler } from './change-password';
import { forgotPasswordHandler } from './forgot-password';
import { resetPasswordHandler } from './reset-password';
import { bootstrapHandler } from './bootstrap';
import { usersMe } from './users-me';
import { panicHandler } from './panic-handler';
import { revokeHandler } from './revoke-handler';
import { passkeyRouter } from './passkey-router';

export const authRouter = createRouter();

authRouter.use(bodyParser());
// After the body parser (it reads the claimed identity out of the body) and before everything else, so
// that a probe rejected by the rate limiter is recorded too. Observes only.
authRouter.use(authAudit);
// Extracts the Origin (or derives it from Referer) for the handlers that log it. Not a check — origin
// validation was removed on 2026-08-13.
authRouter.use(originMiddleware);

authRouter.use('/', async (ctx) => ctx.json({ officerAuthServer: 'ok' }));

authRouter.get('/me', userMiddleware, usersMe);
authRouter.post('/signin', signinRateLimiter, signinHandler);
authRouter.post('/signout', userMiddleware, signoutHandler);
// Revoke the current token — blacklists this JWT (same effect as signout), logged as a security
// event. The app's "distress".
authRouter.post('/revoke', userMiddleware, revokeHandler);
// Trigger the panic lockdown — authenticated, no password in the body.
authRouter.post('/panic', userMiddleware, panicHandler);
// Creates the single server-owner account. Only succeeds while the user table is empty.
authRouter.post('/bootstrap', signupRateLimiter, bootstrapHandler);
// Validates a password-reset link before the reset form is shown.
authRouter.post('/verify-token', verifyTokenHandler);
authRouter.post('/change-password', userMiddleware, changePasswordHandler);
authRouter.post('/forgot-password', forgotPasswordRateLimiter, forgotPasswordHandler);
authRouter.post('/reset-password', resetPasswordHandler);
authRouter.route('/passkeys', passkeyRouter);
