import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { ProfitCenterNotFoundError, InvalidStateError } from "../lib/errors.generated";
import { baseProfitCenter, activeProfitCenter, inactiveProfitCenter } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./deleteProfitCenter";

describe("deleteProfitCenter", () => {
  it("deletes a DRAFT profit center successfully", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseProfitCenter);

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

    const value = expectOk(result);
    expect(value.profitCenter).toEqual(baseProfitCenter);
    expect(spies.delete).toHaveBeenCalled();
  });

  it("deletes a DRAFT profit center and removes its hierarchy assignment", async () => {
    const pcWithNode = { ...baseProfitCenter, hierarchyNodeId: "pc-node-child-1" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(pcWithNode);

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

    expectOk(result);
    expect(spies.delete).toHaveBeenCalled();
  });

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

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

    expectErr(result, ProfitCenterNotFoundError);
  });

  it("returns error when profit center is in ACTIVE status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activeProfitCenter);

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

    expectErr(result, InvalidStateError);
  });

  it("returns error when profit center is in INACTIVE status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactiveProfitCenter);

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

    expectErr(result, InvalidStateError);
  });

  it("emits audit event recording the deletion and acting user", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseProfitCenter);

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

    expectOk(result);
    expect(spies.delete).toHaveBeenCalled();
  });
});
