// @vitest-environment happy-dom
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, renderHook, waitFor } from "@testing-library/react";
import { useLineReconciliation } from "./useLineReconciliation";

afterEach(() => {
  cleanup();
  vi.unstubAllGlobals();
});

describe("useLineReconciliation", () => {
  it("fetches the line reconciliation data on mount", async () => {
    const fixture = {
      claimId: "CLM-1",
      summary: {
        billedTotal: "100",
        paidTotal: "80",
        adjustmentTotal: "20",
        matchedLines: 1,
        totalLines: 1,
      },
      lines: [],
    };
    vi.stubGlobal(
      "fetch",
      vi.fn().mockResolvedValue({
        ok: true,
        json: async () => fixture,
      })
    );
    const { result } = renderHook(() => useLineReconciliation("CLM-1"));
    await waitFor(() => expect(result.current.loading).toBe(false));
    expect(result.current.data).toEqual(fixture);
  });

  it("returns null when claimId is null", () => {
    const { result } = renderHook(() => useLineReconciliation(null));
    expect(result.current.data).toBeNull();
    expect(result.current.loading).toBe(false);
  });

  it("exposes an error when fetch fails", async () => {
    vi.stubGlobal(
      "fetch",
      vi.fn().mockResolvedValue({
        ok: false,
        status: 500,
        json: async () => ({}),
      })
    );
    const { result } = renderHook(() => useLineReconciliation("CLM-1"));
    await waitFor(() => expect(result.current.error).not.toBeNull());
  });
});
