import { describe, expect, it, vi } from "vitest";
import { reactive } from "vue";
import { useMdtodoViewState } from "./useMdtodoViewState";

function setup(query: Record<string, string> = {}) {
  const route = reactive({
    name: "ProjectMdtodoTask",
    params: { sourceId: "source", fileRef: "file", taskId: "R1" },
    query,
    fullPath: "/projects/mdtodo/source/file/R1",
  });
  const router = {
    resolve: vi.fn((navigation: { query: Record<string, unknown> }) => ({
      fullPath: JSON.stringify(navigation.query),
    })),
    push: vi.fn(),
    replace: vi.fn(),
  };
  return {
    route,
    router,
    state: useMdtodoViewState(router as never, route as never),
  };
}

describe("useMdtodoViewState", () => {
  it("provides stable defaults", () => {
    const { state } = setup();
    expect(state.view.value).toBe("workspace");
    expect(state.tab.value).toBe("document");
    expect(state.search.value).toBe("");
    expect(state.status.value).toBe("all");
  });

  it("pushes view and tab changes", async () => {
    const { router, state } = setup();
    await state.update({ view: "queue", tab: "tasks" });
    expect(router.push).toHaveBeenCalledWith(
      expect.objectContaining({ query: { view: "queue", tab: "tasks" } }),
    );
  });

  it("replaces text filters and clears default query values", async () => {
    const { router, state } = setup({
      view: "queue",
      tab: "tasks",
      q: "old",
      status: "completed",
    });
    await state.update(
      { view: "workspace", tab: "document", search: "", status: "all" },
      true,
    );
    expect(router.replace).toHaveBeenCalledWith(
      expect.objectContaining({ query: {} }),
    );
  });

  it("does not write duplicate history", async () => {
    const { route, router, state } = setup({ view: "queue" });
    route.fullPath = JSON.stringify({ view: "queue" });
    await state.update({ view: "queue" });
    expect(router.push).not.toHaveBeenCalled();
    expect(router.replace).not.toHaveBeenCalled();
  });
});
