import { describe, it, expect, vi, beforeEach } from "vitest";
import { AuthMiddleware } from "./auth.middleware.js";
import type { AuthenticatedRequest } from "./auth.middleware.js";
import { UnauthorizedException } from "@nestjs/common";
import type { Response, NextFunction } from "express";

describe("AuthMiddleware", () => {
  let middleware: AuthMiddleware;
  const next = vi.fn();

  beforeEach(() => {
    vi.clearAllMocks();
    middleware = new AuthMiddleware();
  });

  function createReq(headers: Record<string, unknown>): AuthenticatedRequest {
    return { headers } as unknown as AuthenticatedRequest;
  }

  it("should set userId and userRoles from headers", () => {
    const req = createReq({
      "x-user-id": "user-1",
      "x-user-roles": "admin,teacher",
    });
    middleware.use(req, {} as Response, next as NextFunction);
    expect(req.userId).toBe("user-1");
    expect(req.userRoles).toEqual(["admin", "teacher"]);
    expect(next).toHaveBeenCalled();
  });

  it("should set empty roles array when x-user-roles missing", () => {
    const req = createReq({ "x-user-id": "user-1" });
    middleware.use(req, {} as Response, next as NextFunction);
    expect(req.userId).toBe("user-1");
    expect(req.userRoles).toEqual([]);
  });

  it("should throw UnauthorizedException when x-user-id missing", () => {
    const req = createReq({});
    expect(() =>
      middleware.use(req, {} as Response, next as NextFunction),
    ).toThrow(UnauthorizedException);
  });

  it("should throw when x-user-id is not a string", () => {
    const req = createReq({ "x-user-id": ["not-a-string"] });
    expect(() =>
      middleware.use(req, {} as Response, next as NextFunction),
    ).toThrow(UnauthorizedException);
  });

  it("should not call next when unauthorized", () => {
    const req = createReq({});
    expect(() =>
      middleware.use(req, {} as Response, next as NextFunction),
    ).toThrow();
    expect(next).not.toHaveBeenCalled();
  });
});
