import { beforeEach, describe, expect, it, vi } from "vitest";
import { GET } from "./route";
import { ApiV1Error } from "@/lib/api-v1/errors";

const mocks = vi.hoisted(() => ({
  requireApiV1Auth: vi.fn(),
}));

vi.mock("@/lib/api-v1/auth", () => ({
  requireApiV1Auth: mocks.requireApiV1Auth,
}));

describe("GET /api/v1/auth/me", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("retorna contexto autenticado", async () => {
    mocks.requireApiV1Auth.mockResolvedValue({
      user: { id: "user-1", email: "user@example.com" },
      companyContext: {
        companyId: "company-1",
        ownerId: "owner-1",
        tenantIds: ["company-1", "owner-1"],
        membership: { permissions: {}, role: "admin", active: true, companyId: "company-1" },
      },
    });

    const response = await GET(new Request("http://localhost/api/v1/auth/me"));
    expect(response.status).toBe(200);
    await expect(response.json()).resolves.toMatchObject({
      success: true,
      data: {
        user: { id: "user-1", email: "user@example.com" },
        company: { id: "company-1" },
      },
    });
  });

  it("nega acesso sem autenticacao", async () => {
    mocks.requireApiV1Auth.mockRejectedValue(new ApiV1Error(401, "missing_bearer_token", "Token Bearer obrigatorio."));

    const response = await GET(new Request("http://localhost/api/v1/auth/me"));
    expect(response.status).toBe(401);
    await expect(response.json()).resolves.toMatchObject({
      success: false,
      error: { code: "missing_bearer_token" },
    });
  });
});
