/**
 * Verifies the access JWT on `Authorization: Bearer <token>` and puts
 * `{ id, role }` on `req.admin`. Stateless — no DB hit; the 15-minute token TTL
 * bounds staleness (a deactivated admin is fully cut off within that window and
 * immediately on their next refresh).
 *
 * Throws AppError so errorHandler stays the one place a body is written (§5).
 */
import type { NextFunction, Request, Response } from 'express';
import { AppError } from '../lib/AppError';
import { verifyAccessToken } from '../modules/auth/token.service';

export function authenticate(req: Request, _res: Response, next: NextFunction): void {
  const header = req.get('authorization');
  if (!header || !header.startsWith('Bearer ')) {
    next(AppError.unauthorized('Missing bearer token'));
    return;
  }
  try {
    const claims = verifyAccessToken(header.slice(7).trim());
    req.admin = { id: claims.sub, role: claims.role };
    next();
  } catch (err) {
    next(err);
  }
}
