import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { InternalOrderNotFoundError, InvalidStateError } from "../lib/errors.generated";
import {
  baseInternalOrder,
  releasedInternalOrder,
  techCompletedInternalOrder,
  closedInternalOrder,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./closeInternalOrder";

describe("closeInternalOrder", () => {
  it("closes a TECHNICALLY_COMPLETED internal order transitioning it to CLOSED status", async () => {
    const updated = { ...techCompletedInternalOrder, status: "CLOSED" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(techCompletedInternalOrder);
    spies.update.mockReturnValueOnce(updated);

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

    const value = expectOk(result);
    expect(value.internalOrder.status).toBe("CLOSED");
  });

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

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

    expectErr(result, InternalOrderNotFoundError);
  });

  it("returns error when internal order is in CREATED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseInternalOrder);

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

    expectErr(result, InvalidStateError);
  });

  it("returns error when internal order is in RELEASED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(releasedInternalOrder);

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

    expectErr(result, InvalidStateError);
  });

  it("returns error when internal order is already CLOSED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(closedInternalOrder);

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

    expectErr(result, InvalidStateError);
  });

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

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

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