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

export interface AuthenticatedRequest extends Request {
  userId?: string;
  userRoles?: string[];
}

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  use(req: AuthenticatedRequest, res: Response, next: NextFunction): void {
    // 从 Gateway 注入的头部读取用户信息
    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;

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

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