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

describe("recallPurchaseRequisition", () => {
  it("recalls a submitted purchase requisition back to draft", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const ctx = { ...commandCtx, actorId: submittedPurchaseRequisition.requesterId };
    spies.select.mockReturnValueOnce(submittedPurchaseRequisition);
    spies.update.mockReturnValueOnce({
      ...submittedPurchaseRequisition,
      status: "DRAFT",
    });

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

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

  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" }, 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 }, commandCtx);

    expectErr(result, PurchaseRequisitionNotSubmittedError);
  });

  it("returns error when caller is not the original requester", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedPurchaseRequisition);
    const ctx = { ...commandCtx, actorId: "someone-else" };

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

    expectErr(result, RecallNotAuthorizedError);
  });
});
