import { waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "../test/testHelpers";
import { ClientMagicLinkExchangePage } from "./ClientMagicLinkExchangePage";

const originalLocation = window.location;

describe("ClientMagicLinkExchangePage", () => {
  const replaceMock = vi.fn();

  beforeEach(() => {
    vi.clearAllMocks();
    vi.stubEnv("VITE_API_URL", "https://api-staging.xtablo.com");

    Object.defineProperty(window, "location", {
      configurable: true,
      value: {
        ...originalLocation,
        replace: replaceMock,
      },
    });
  });

  afterEach(() => {
    vi.unstubAllEnvs();
    Object.defineProperty(window, "location", {
      configurable: true,
      value: originalLocation,
    });
  });

  it("hands the token off to the API exchange endpoint", async () => {
    renderWithProviders(<ClientMagicLinkExchangePage />, {
      path: "/auth/exchange",
      route: "/auth/exchange?token=magic-token-123",
      testUser: undefined,
    });

    await waitFor(() => {
      expect(replaceMock).toHaveBeenCalledWith(
        "https://api-staging.xtablo.com/api/v1/client-auth/exchange?token=magic-token-123"
      );
    });
  });
});
