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 "./deactivateProfitCenter";

describe("deactivateProfitCenter", () => {
  it("deactivates an ACTIVE profit center transitioning it to INACTIVE status", async () => {
    const deactivated = { ...activeProfitCenter, status: "INACTIVE" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activeProfitCenter);
    spies.update.mockReturnValueOnce(deactivated);

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

    const value = expectOk(result);
    expect(value.profitCenter.status).toBe("INACTIVE");
  });

  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 DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseProfitCenter);

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

    expectErr(result, InvalidStateError);
  });

  it("returns error when profit center is already INACTIVE", 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 status transition and acting user", async () => {
    const deactivated = { ...activeProfitCenter, status: "INACTIVE" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activeProfitCenter);
    spies.update.mockReturnValueOnce(deactivated);

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

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