import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, test } from "vitest";
import { externalApiHandlers } from "./external-api-mocks";

const server = setupServer(...externalApiHandlers);

describe("external API mocks", () => {
  beforeAll(() => {
    server.listen({ onUnhandledRequest: "error" });
  });

  afterEach(() => {
    server.resetHandlers();
  });

  afterAll(() => {
    server.close();
  });

  test("defines deterministic handlers for deferred datasource adapters", () => {
    expect(externalApiHandlers).toHaveLength(3);
    expect(externalApiHandlers.map((handler) => handler.info.header)).toEqual([
      "GET https://prometheus.dimensionlab.net/api/v1/query",
      "GET https://uptime.dimensionlab.net/api/status-page/*",
      "GET https://api.open-meteo.com/v1/forecast",
    ]);
  });

  test("intercepts deferred datasource requests without live services", async () => {
    const prometheus = await fetch(
      "https://prometheus.dimensionlab.net/api/v1/query",
    ).then((response) => response.json());
    const status = await fetch(
      "https://uptime.dimensionlab.net/api/status-page/dimensionlab",
    ).then((response) => response.json());
    const weather = await fetch(
      "https://api.open-meteo.com/v1/forecast?latitude=52.37&longitude=4.9",
    ).then((response) => response.json());

    expect(prometheus).toMatchObject({
      status: "success",
      data: { result: [{ value: [1771430400, "1"] }] },
    });
    expect(status).toMatchObject({
      status: "ok",
      incidents: [],
    });
    expect(weather).toMatchObject({
      current: {
        temperature_2m: 21.4,
        weather_code: 0,
      },
    });
  });
});
