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

describe("getProfitCenter", () => {
  it("returns profit center with all fields when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select
      .mockReturnValueOnce(baseProfitCenter)
      .mockReturnValueOnce([baseProfitCenterHierarchyAssignment]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.profitCenter).toEqual(baseProfitCenter);
    }
  });

  it("returns profit center with hierarchy node assignment populated", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select
      .mockReturnValueOnce(baseProfitCenter)
      .mockReturnValueOnce([baseProfitCenterHierarchyAssignment]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.hierarchyAssignments).toEqual([baseProfitCenterHierarchyAssignment]);
      expect(result.value.hierarchyAssignments[0]).toMatchObject({
        profitCenterId: baseProfitCenter.id,
        hierarchyNodeId: baseProfitCenterHierarchyAssignment.hierarchyNodeId,
      });
    }
  });

  it("returns profit center with responsible person and validity period", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseProfitCenter).mockReturnValueOnce([]);

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

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

  it("returns null when no profit 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.profitCenter).toBeNull();
      expect(result.value.hierarchyAssignments).toEqual([]);
    }
  });
});
