import { render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider, createTheme } from "@mui/material";
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest";
import App from "../src/App";

const originalFetch = globalThis.fetch;

const createResponse = (payload: unknown) =>
  new Response(JSON.stringify(payload), {
    status: 200,
    headers: { "Content-Type": "application/json" }
  });

describe("App", () => {
  beforeEach(() => {
    globalThis.fetch = vi.fn((url: string) => {
      if (url === "/api/locations") {
        return Promise.resolve(createResponse([{ name: "westeurope", displayName: "West Europe" }]));
      }

      if (url === "/api/templates") {
        return Promise.resolve(createResponse([{ label: "Azure CLI", language: "shell", file: "shell.tpl" }]));
      }

      return Promise.resolve(createResponse([]));
    }) as typeof fetch;
  });

  afterEach(() => {
    globalThis.fetch = originalFetch;
  });

  it("renders application heading", async () => {
    const client = new QueryClient({
      defaultOptions: {
        queries: {
          retry: false,
          gcTime: 0
        }
      }
    });
    const theme = createTheme();

    const view = render(
      <QueryClientProvider client={client}>
        <ThemeProvider theme={theme}>
          <App />
        </ThemeProvider>
      </QueryClientProvider>
    );

    expect(await screen.findByText("Azure Image Chooser")).toBeInTheDocument();
    view.unmount();
    client.clear();
  });
});
