import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CostCenterNotFoundError,
  CostCenterHasPostingsError,
  CostCenterHasBudgetItemsError,
  CostCenterHasAllocationRulesError,
} from "../lib/errors.generated";
import {
  baseCostCenter,
  baseAllocationResult,
  baseBudget,
  baseAllocationRule,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./deleteCostCenter";

describe("deleteCostCenter", () => {
  it("returns error when cost center does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { costCenterId: "missing-cc" }, commandCtx);

    expectErr(result, CostCenterNotFoundError);
  });

  it("returns error when cost center has postings", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseCostCenter) // cost center exists
      .mockReturnValueOnce(baseAllocationResult); // has postings

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

    expectErr(result, CostCenterHasPostingsError);
  });

  it("returns error when cost center has budget items", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseCostCenter) // cost center exists
      .mockReturnValueOnce(undefined) // no postings
      .mockReturnValueOnce(baseBudget); // has budget

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

    expectErr(result, CostCenterHasBudgetItemsError);
  });

  it("returns error when cost center has allocation rules", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseCostCenter) // cost center exists
      .mockReturnValueOnce(undefined) // no postings
      .mockReturnValueOnce(undefined) // no budgets
      .mockReturnValueOnce(baseAllocationRule); // has allocation rules

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

    expectErr(result, CostCenterHasAllocationRulesError);
  });

  it("deletes cost center when no dependencies exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseCostCenter) // cost center exists
      .mockReturnValueOnce(undefined) // no postings
      .mockReturnValueOnce(undefined) // no budgets
      .mockReturnValueOnce(undefined); // no allocation rules

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

    const value = expectOk(result);
    expect(value.costCenterId).toBe(baseCostCenter.id);
    expect(spies.delete).toHaveBeenCalled();
  });
});
