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

describe("getAccountGroup", () => {
  it("returns group when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(baseRootGroup);

    const result = await run(db, { id: baseRootGroup.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountGroup).toEqual(baseRootGroup);
    }
  });

  it("returns null when group not found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(undefined);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountGroup).toBeNull();
    }
  });

  it("returns group when found by code within CoA", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(baseChildGroup);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountGroup).toEqual(baseChildGroup);
    }
  });

  it("returns null when group not found by code within CoA", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(undefined);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountGroup).toBeNull();
    }
  });
});
