import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { CoNotFoundError, CoNotSubmittedError } from "../lib/errors.generated";
import { basePurchaseChangeOrder, submittedChangeOrder } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./rejectPurchaseChangeOrder";

describe("rejectPurchaseChangeOrder", () => {
  it("rejects a valid submitted change order with a rejection reason", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const rejected = { ...submittedChangeOrder, changeOrderStatus: "DRAFT" };
    spies.select.mockReturnValueOnce(submittedChangeOrder);
    spies.update.mockReturnValueOnce(rejected);

    const result = await run(
      db,
      { id: submittedChangeOrder.id, rejectionReason: "Prices too high" },
      commandCtx,
    );

    expect(expectOk(result).changeOrder.changeOrderStatus).toBe("DRAFT");
  });

  it("returns the change order to DRAFT status after rejection", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const rejected = { ...submittedChangeOrder, changeOrderStatus: "DRAFT" };
    spies.select.mockReturnValueOnce(submittedChangeOrder);
    spies.update.mockReturnValueOnce(rejected);

    const result = await run(
      db,
      { id: submittedChangeOrder.id, rejectionReason: "Renegotiate" },
      commandCtx,
    );

    expect(expectOk(result).changeOrder.changeOrderStatus).toBe("DRAFT");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ changeOrderStatus: "DRAFT", rejectionReason: "Renegotiate" }),
    );
  });

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

    const result = await run(db, { id: "missing-co", rejectionReason: "N/A" }, commandCtx);

    expectErr(result, CoNotFoundError);
  });

  it("returns error when change order is not in SUBMITTED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePurchaseChangeOrder); // DRAFT

    const result = await run(
      db,
      { id: basePurchaseChangeOrder.id, rejectionReason: "Wrong" },
      commandCtx,
    );

    expectErr(result, CoNotSubmittedError);
  });
});
