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

describe("deleteCostElement", () => {
  it("deletes a DRAFT cost element successfully", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCostElement);
    spies.delete.mockReturnValueOnce(undefined);

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

    const value = expectOk(result);
    expect(value.costElement).toEqual(baseCostElement);
  });

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

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

    expectErr(result, InvalidStateError);
  });

  it("returns error when cost element is in INACTIVE status", 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 deletion and acting user", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCostElement);
    spies.delete.mockReturnValueOnce(undefined);

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

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