import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  PurchaseRequisitionNotFoundError,
  PurchaseRequisitionNotSubmittedError,
  SelfApprovalNotAllowedError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { basePurchaseRequisition, submittedPurchaseRequisition } from "../testing/fixtures";
import { run } from "./approvePurchaseRequisition";

describe("approvePurchaseRequisition", () => {
  it("approves a valid submitted purchase requisition", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [submittedPurchaseRequisition],
      [{ ...submittedPurchaseRequisition, status: "APPROVED" }],
    );

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

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

  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 approver is the same as the requester", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([submittedPurchaseRequisition]);
    const ctx = { ...commandCtx, actorId: submittedPurchaseRequisition.requesterId };

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

    expectErr(result, SelfApprovalNotAllowedError);
  });
});
