import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseRootGroup, baseChildGroup, baseGroupNoRange } from "../testing/fixtures";
import { run } from "./listAccountGroups";

describe("listAccountGroups", () => {
  it("returns all groups in a CoA when no parent filter applied", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseRootGroup, baseChildGroup, baseGroupNoRange]);

    const result = await run(db, { chartOfAccountsId: "coa-2" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseRootGroup, baseChildGroup, baseGroupNoRange]);
    }
  });

  it("returns root groups when parent filter is null", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseRootGroup, baseGroupNoRange]);

    const result = await run(db, { chartOfAccountsId: "coa-2", parentAccountGroupId: null });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseRootGroup, baseGroupNoRange]);
    }
  });

  it("returns child groups of a specific parent", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseChildGroup]);

    const result = await run(db, {
      chartOfAccountsId: "coa-2",
      parentAccountGroupId: "group-1",
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseChildGroup]);
    }
  });

  it("returns groups sorted by sort order", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseRootGroup, baseGroupNoRange]);

    const result = await run(db, { chartOfAccountsId: "coa-2", parentAccountGroupId: null });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items[0]).toEqual(baseRootGroup);
      expect(result.value.items[1]).toEqual(baseGroupNoRange);
    }
  });

  it("returns empty list when no groups match", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);

    const result = await run(db, { chartOfAccountsId: "nonexistent" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([]);
      expect(result.value.hasNextPage).toBe(false);
    }
  });
});
