import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    const ctx = { ...commandCtx, actorId: submittedPurchaseRequisition.requesterId };
    mock.enqueueResults(
      [submittedPurchaseRequisition],
      [{ ...submittedPurchaseRequisition, status: "DRAFT" }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: submittedPurchaseRequisition.id }, ctx),
    );

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

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

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

    expectErr(result, PurchaseRequisitionNotFoundError);
  });

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

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

    expectErr(result, PurchaseRequisitionNotSubmittedError);
  });

  it("returns error when caller is not the original requester", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([submittedPurchaseRequisition]);
    const ctx = { ...commandCtx, actorId: "someone-else" };

    const result = await mock.withTx((trx) =>
      run(trx, { id: submittedPurchaseRequisition.id }, ctx),
    );

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