import {
  Injectable,
  NestMiddleware,
  UnauthorizedException,
} from "@nestjs/common";
import type { Request, Response, NextFunction } from "express";

/**
 * 已认证请求：由 AuthMiddleware 从 Gateway 注入的 x-user-* 头部解析。
 * 公开端点（login/register/refresh/jwks/health）不走此中间件。
 */
export interface AuthenticatedRequest extends Request {
  userId?: string;
  userRoles?: string[];
  userDataScope?: string;
}

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  use(req: AuthenticatedRequest, _res: Response, next: NextFunction): void {
    const userIdHeader = req.headers["x-user-id"];
    const userId = typeof userIdHeader === "string" ? userIdHeader : undefined;
    const rolesHeaderRaw = req.headers["x-user-roles"];
    const rolesHeader =
      typeof rolesHeaderRaw === "string" ? rolesHeaderRaw : undefined;
    const dataScopeHeaderRaw = req.headers["x-user-data-scope"];
    const dataScopeHeader =
      typeof dataScopeHeaderRaw === "string" ? dataScopeHeaderRaw : undefined;

    if (!userId) {
      throw new UnauthorizedException("Missing x-user-id header");
    }

    req.userId = userId;
    req.userRoles = rolesHeader ? rolesHeader.split(",") : [];
    req.userDataScope = dataScopeHeader ?? "self";
    next();
  }
}
