import type { NextFunction, Request, Response } from 'express';
import { verifyAgentToken, type AgentClaims } from './jwt.js';
import { unauthorized, forbidden } from '../utils/errors.js';

declare global {
  // eslint-disable-next-line @typescript-eslint/no-namespace
  namespace Express {
    interface Request {
      agent?: AgentClaims;
    }
  }
}

function bearer(req: Request): string | null {
  const header = req.headers.authorization;
  if (header?.startsWith('Bearer ')) return header.slice(7);
  // Cookie fallback keeps <img>/<a> style file downloads working in the dashboard.
  const cookie = (req as any).cookies?.token;
  return typeof cookie === 'string' ? cookie : null;
}

/** Requires a valid agent JWT; attaches claims to `req.agent`. */
export function requireAgent(req: Request, _res: Response, next: NextFunction) {
  const token = bearer(req);
  if (!token) return next(unauthorized('Missing authorization token'));
  try {
    req.agent = verifyAgentToken(token);
    next();
  } catch (err) {
    next(err);
  }
}

export function requireAdmin(req: Request, _res: Response, next: NextFunction) {
  if (req.agent?.role !== 'admin') return next(forbidden('Admin role required'));
  next();
}
