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

describe("approvePurchaseRequisition", () => {
  it("approves a valid submitted purchase requisition", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedPurchaseRequisition);
    spies.update.mockReturnValueOnce({
      ...submittedPurchaseRequisition,
      status: "APPROVED",
    });

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

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

  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 approver is the same as the requester", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedPurchaseRequisition);
    const ctx = { ...commandCtx, actorId: submittedPurchaseRequisition.requesterId };

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

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