import { beforeEach, describe, expect, it, vi } from "vitest";

const { mockGet, mockCreate } = vi.hoisted(() => ({
  mockGet: vi.fn(),
  mockCreate: vi.fn(),
}));

vi.mock("axios", () => ({
  default: { create: mockCreate },
  create: mockCreate,
}));

import { auth } from "./auth";

describe("auth module", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockCreate.mockReturnValue({ get: mockGet });
  });

  it("fetches auth redirect uri and callback key", async () => {
    mockGet.mockResolvedValueOnce({
      data: {
        data: {
          uri: "https://auth.example.com",
          callbackKey: "cb-123",
        },
      },
    });

    const result = await auth.fetchAuthRedirectUri("https://api.example.com");

    expect(mockCreate).toHaveBeenCalledWith({
      baseURL: "https://api.example.com",
      timeout: 5000,
    });
    expect(mockGet).toHaveBeenCalledWith("/v1/auth/uri");
    expect(result).toEqual({
      uri: "https://auth.example.com",
      callbackKey: "cb-123",
    });
  });

  it("throws wrapped error when response is missing uri", async () => {
    mockGet.mockResolvedValueOnce({ data: { data: {} } });

    await expect(
      auth.fetchAuthRedirectUri("https://api.example.com"),
    ).rejects.toThrow(
      "Failed to fetch auth redirect uri: redirect uri missing from response",
    );
  });

  it("throws wrapped axios error message", async () => {
    mockGet.mockRejectedValueOnce(new Error("network down"));

    await expect(
      auth.fetchAuthRedirectUri("https://api.example.com"),
    ).rejects.toThrow("Failed to fetch auth redirect uri: network down");
  });
});
