import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PurchaseRequisitionNotFoundError,
  PurchaseRequisitionNotSubmittedError,
  RejectionReasonRequiredError,
} from "../lib/errors.generated";
import { basePurchaseRequisition, submittedPurchaseRequisition } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./rejectPurchaseRequisition";

describe("rejectPurchaseRequisition", () => {
  it("rejects a submitted purchase requisition back to draft", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedPurchaseRequisition);
    spies.update.mockReturnValueOnce({
      ...submittedPurchaseRequisition,
      status: "DRAFT",
      rejectionReason: "Budget exceeded",
    });

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

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

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

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

    expect(expectOk(result).purchaseRequisition.rejectionReason).toBe("Not justified");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ rejectionReason: "Not justified" }),
    );
  });

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

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

    expectErr(result, PurchaseRequisitionNotFoundError);
  });

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

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

    expectErr(result, PurchaseRequisitionNotSubmittedError);
  });

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

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

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