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

describe("getCostCenter", () => {
  it("returns cost center with all fields and hierarchy node assignment when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseCostCenter).mockReturnValueOnce(childCostCenterNode);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.costCenter).toEqual(baseCostCenter);
      if (result.value.costCenter !== null) {
        expect(
          (result.value as { costCenter: typeof baseCostCenter; hierarchyNode: unknown })
            .hierarchyNode,
        ).toEqual(childCostCenterNode);
      }
    }
  });

  it("returns cost center with responsible person and department reference populated", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseCostCenter).mockReturnValueOnce(childCostCenterNode);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.costCenter?.responsiblePersonId).not.toBeNull();
      expect(result.value.costCenter?.departmentId).not.toBeNull();
    }
  });

  it("returns null when no cost center matches the given id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "non-existent" });

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