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

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

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

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

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

    const result = await run(db, { costElementId: inactiveCostElement.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(activeCostElement);
    spies.update.mockReturnValueOnce({ ...activeCostElement, status: "INACTIVE" });

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

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