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

describe("reactivateProfitCenter", () => {
  it("reactivates an INACTIVE profit center transitioning it to ACTIVE status", async () => {
    const reactivated = { ...inactiveProfitCenter, status: "ACTIVE" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactiveProfitCenter);
    spies.update.mockReturnValueOnce(reactivated);

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

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

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

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

    expectErr(result, InvalidStateError);
  });

  it("emits audit event recording the status transition and acting user", async () => {
    const reactivated = { ...inactiveProfitCenter, status: "ACTIVE" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactiveProfitCenter);
    spies.update.mockReturnValueOnce(reactivated);

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

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