import { render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";

import { TerminalNavLink } from "~/components/TerminalNavLink";
import {
  COURSEWARE_RUNTIME_CONFIG_PATH,
  LAB3_DEFAULT_TERMINAL_PATH,
} from "~/lib/courseware-runtime";

describe("TerminalNavLink", () => {
  afterEach(() => {
    vi.restoreAllMocks();
  });

  it("defaults to the same-origin WeTTY path", () => {
    vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("not found"));

    render(<TerminalNavLink />);

    expect(screen.getByRole("link", { name: "Terminal" })).toHaveAttribute(
      "href",
      LAB3_DEFAULT_TERMINAL_PATH,
    );
  });

  it("loads the terminal link from runtime config", async () => {
    const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
      new Response(
        JSON.stringify({
          lab3TerminalUrl: "http://127.0.0.1:7681/wetty",
        }),
        { status: 200 },
      ),
    );

    render(<TerminalNavLink />);

    await waitFor(() => {
      expect(screen.getByRole("link", { name: "Terminal" })).toHaveAttribute(
        "href",
        "http://localhost:7681/wetty",
      );
    });
    expect(fetchMock).toHaveBeenCalledWith(COURSEWARE_RUNTIME_CONFIG_PATH, {
      cache: "no-store",
    });
  });
});
