import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidOrderStatusError, RejectionReasonRequiredError } from "../lib/errors.generated";
import { submittedSalesOrder } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./rejectSalesOrder";

describe("rejectSalesOrder", () => {
  it("rejects a submitted order and returns it to DRAFT", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const rejected = {
      ...submittedSalesOrder,
      status: "DRAFT",
      rejectionReason: "Missing approval",
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    spies.select.mockReturnValueOnce(submittedSalesOrder);
    spies.update.mockReturnValueOnce(rejected);

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

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

  it("stores the rejection reason", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reason = "Pricing discrepancy";
    spies.select.mockReturnValueOnce(submittedSalesOrder);
    spies.update.mockReturnValueOnce({
      ...submittedSalesOrder,
      status: "DRAFT",
      rejectionReason: reason,
    });

    const result = await run(
      db,
      { salesOrderId: submittedSalesOrder.id, rejectionReason: reason },
      commandCtx,
    );

    expectOk(result);
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ rejectionReason: reason, status: "DRAFT" }),
    );
  });

  it("throws when rejecting an order outside SUBMITTED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...submittedSalesOrder, status: "CONFIRMED" });

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

    expectErr(result, InvalidOrderStatusError);
  });

  it("throws when rejection reason is empty", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedSalesOrder);

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

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