import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { CostElementNotFoundError, InvalidStateError } from "../lib/errors.generated";
import { baseCostElement, activeCostElement, inactiveCostElement } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./reactivateCostElement";

describe("reactivateCostElement", () => {
  it("reactivates an INACTIVE cost element transitioning it to ACTIVE status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactiveCostElement);
    const updated = { ...inactiveCostElement, status: "ACTIVE" };
    spies.update.mockReturnValueOnce(updated);

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

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

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

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

    expectErr(result, CostElementNotFoundError);
  });

  it("returns error when cost element is in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCostElement);

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

    expectErr(result, InvalidStateError);
  });

  it("returns error when cost element is already ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activeCostElement);

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

    expectErr(result, InvalidStateError);
  });

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

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

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