import { renderHook, waitFor } from "@testing-library/react";
import { useTimelineTimeConfig, toTimelineTimeConfig } from "./useTimelineTimeConfig";

const apiFetch = jest.fn();

jest.mock("@/lib/apiFetch", () => ({
  apiFetch: (...args: unknown[]) => apiFetch(...args),
}));

jest.mock("@/contexts/ProjectContext", () => ({
  useProject: () => ({ networkName: "test-network" }),
}));

describe("useTimelineTimeConfig", () => {
  beforeEach(() => {
    apiFetch.mockReset();
  });

  it("derives duration and step from backend time properties", async () => {
    apiFetch.mockResolvedValueOnce({
      ok: true,
      json: async () => ({
        DURATION: "24:00",
        "HYDRAULIC TIMESTEP": "1:00",
      }),
    });

    const { result } = renderHook(() => useTimelineTimeConfig());

    await waitFor(() => {
      expect(result.current.stepMinutes).toBe(60);
    });
    expect(result.current.durationMinutes).toBe(1440);
    expect(String(apiFetch.mock.calls[0][0])).toContain(
      "/api/v1/network-options/time",
    );
  });

  it("falls back when fetching time properties fails", async () => {
    apiFetch.mockRejectedValueOnce(new Error("network failure"));
    const warnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});

    const { result } = renderHook(() => useTimelineTimeConfig());

    await waitFor(() => {
      expect(apiFetch).toHaveBeenCalledTimes(1);
    });
    expect(result.current).toMatchObject({
      durationMinutes: 1440,
      stepMinutes: 15,
    });

    warnSpy.mockRestore();
  });

  it("parses wrapped times payloads", () => {
    expect(
      toTimelineTimeConfig({
        times: {
          DURATION: "24:00",
          "HYDRAULIC TIMESTEP": "0:05",
        },
      }),
    ).toMatchObject({
      durationMinutes: 1440,
      stepMinutes: 5,
    });
  });
});
