import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PurchaseOrderNotFoundError,
  PurchaseOrderNotSubmittedError,
  RejectionReasonRequiredError,
} from "../lib/errors.generated";
import { basePurchaseOrder, submittedPurchaseOrder } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./rejectPurchaseOrder";

describe("rejectPurchaseOrder", () => {
  it("rejects a submitted purchase order back to draft", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedPurchaseOrder);
    spies.update.mockReturnValueOnce({
      ...submittedPurchaseOrder,
      status: "DRAFT",
      rejectionReason: "Supplier cannot fulfill",
    });

    const result = await run(
      db,
      { id: submittedPurchaseOrder.id, reason: "Supplier cannot fulfill" },
      commandCtx,
    );

    expect(expectOk(result).purchaseOrder.status).toBe("DRAFT");
  });

  it("records the rejection reason for audit", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedPurchaseOrder);
    spies.update.mockReturnValueOnce({
      ...submittedPurchaseOrder,
      status: "DRAFT",
      rejectionReason: "Budget rejected",
    });

    const result = await run(
      db,
      { id: submittedPurchaseOrder.id, reason: "Budget rejected" },
      commandCtx,
    );

    expect(expectOk(result).purchaseOrder.rejectionReason).toBe("Budget rejected");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ rejectionReason: "Budget rejected" }),
    );
  });

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

    const result = await run(db, { id: "missing-order", reason: "No match" }, commandCtx);

    expectErr(result, PurchaseOrderNotFoundError);
  });

  it("returns error when purchase order is not submitted", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePurchaseOrder);

    const result = await run(db, { id: basePurchaseOrder.id, reason: "No match" }, commandCtx);

    expectErr(result, PurchaseOrderNotSubmittedError);
  });

  it("returns error when rejection reason is missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedPurchaseOrder);

    const result = await run(db, { id: submittedPurchaseOrder.id, reason: "   " }, commandCtx);

    expectErr(result, RejectionReasonRequiredError);
  });
});
