import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  PurchaseOrderNotFoundError,
  PurchaseOrderNotSubmittedError,
  RejectionReasonRequiredError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { basePurchaseOrder, submittedPurchaseOrder } from "../testing/fixtures";
import { run } from "./rejectPurchaseOrder";

describe("rejectPurchaseOrder", () => {
  it("rejects a submitted purchase order back to draft", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [submittedPurchaseOrder],
      [
        {
          ...submittedPurchaseOrder,
          orderStatus: "DRAFT",
          rejectionReason: "Supplier cannot fulfill",
        },
      ],
    );

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

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

  it("records the rejection reason for audit", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [submittedPurchaseOrder],
      [{ ...submittedPurchaseOrder, orderStatus: "DRAFT", rejectionReason: "Budget rejected" }],
    );

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

    expect(expectOk(result).purchaseOrder.rejectionReason).toBe("Budget rejected");
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({ rejectionReason: "Budget rejected" }),
    );
  });

  it("returns error when purchase order does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: "missing-order", reason: "No match" }, commandCtx),
    );

    expectErr(result, PurchaseOrderNotFoundError);
  });

  it("returns error when purchase order is not submitted", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePurchaseOrder]);

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

    expectErr(result, PurchaseOrderNotSubmittedError);
  });

  it("returns error when rejection reason is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([submittedPurchaseOrder]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: submittedPurchaseOrder.id, reason: "   " }, commandCtx),
    );

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