// TRACES: UR-052 | DR-143 | UT-140
import { describe, it, expect, vi, beforeEach } from "vitest";
import { writable } from "svelte/store";

const h = vi.hoisted(() => ({
  version: null as ReturnType<typeof import("svelte/store").writable<number>> | null,
  destroyFns: [] as Array<() => void>,
}));

vi.mock("svelte", () => ({
  onDestroy: (fn: () => void) => h.destroyFns.push(fn),
}));

vi.mock("$lib/services/offlineCatalog", () => ({
  get catalogFilterVersion() {
    return h.version;
  },
}));

import { useOfflineFilterReload } from "./useOfflineFilterReload";

describe("useOfflineFilterReload (DR-143)", () => {
  beforeEach(() => {
    h.version = writable(0);
    h.destroyFns.length = 0;
  });

  it("does not reload for the value the page already loaded under", () => {
    const reload = vi.fn();
    useOfflineFilterReload(reload);

    expect(reload).not.toHaveBeenCalled();
  });

  it("reloads once each time the gate settles into a new state", () => {
    const reload = vi.fn();
    useOfflineFilterReload(reload);

    h.version!.set(1);
    expect(reload).toHaveBeenCalledTimes(1);

    h.version!.set(2);
    expect(reload).toHaveBeenCalledTimes(2);
  });

  it("stops reloading a page that has been destroyed", () => {
    const reload = vi.fn();
    useOfflineFilterReload(reload);

    h.destroyFns.forEach((fn) => fn());
    h.version!.set(1);

    expect(reload).not.toHaveBeenCalled();
  });
});
