import { Request, Response, NextFunction } from "express";
import { isValidKey, getKeyInfo } from "../services/keys.js";

export function authMiddleware(
  req: Request,
  res: Response,
  next: NextFunction
): void {
  const header = req.headers.authorization;
  if (!header?.startsWith("Bearer ")) {
    res.status(401).json({ error: "Missing API key. Use: Authorization: Bearer <key>" });
    return;
  }
  const key = header.slice(7);
  if (!isValidKey(key)) {
    res.status(403).json({ error: "Invalid API key" });
    return;
  }
  // Attach key info to request for downstream use
  (req as any).apiKeyInfo = getKeyInfo(key);
  next();
}
