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

describe("rejectSalesOrder", () => {
  it("rejects a submitted order and returns it to DRAFT", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const rejected = {
      ...submittedSalesOrder,
      status: "DRAFT",
      rejectionReason: "Missing approval",
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    mock.enqueueResults([submittedSalesOrder], [rejected]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { salesOrderId: submittedSalesOrder.id, rejectionReason: "Missing approval" },
        commandCtx,
      ),
    );

    const value = expectOk(result);
    expect(value.salesOrder.status).toBe("DRAFT");
  });

  it("stores the rejection reason", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const reason = "Pricing discrepancy";
    mock.enqueueResults(
      [submittedSalesOrder],
      [{ ...submittedSalesOrder, status: "DRAFT", rejectionReason: reason }],
    );

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

    expectOk(result);
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({ rejectionReason: reason, status: "DRAFT" }),
    );
  });

  it("throws when rejecting an order outside SUBMITTED status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...submittedSalesOrder, status: "CONFIRMED" }]);

    const result = await mock.withTx((trx) =>
      run(trx, { salesOrderId: submittedSalesOrder.id, rejectionReason: "Invalid" }, commandCtx),
    );

    expectErr(result, InvalidOrderStatusError);
  });

  it("throws when rejection reason is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([submittedSalesOrder]);

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

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