import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { CoNotFoundError, CoNotSubmittedError } from "../lib/errors.generated";
import {
  basePurchaseChangeOrder,
  submittedChangeOrder,
  approvedChangeOrder,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./approvePurchaseChangeOrder";

describe("approvePurchaseChangeOrder", () => {
  it("approves a valid submitted change order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const approved = { ...submittedChangeOrder, changeOrderStatus: "APPROVED" };
    spies.select.mockReturnValueOnce(submittedChangeOrder);
    spies.update.mockReturnValueOnce(approved);

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

    expect(expectOk(result).changeOrder.changeOrderStatus).toBe("APPROVED");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ changeOrderStatus: "APPROVED" }),
    );
  });

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

    const result = await run(db, { id: "missing-co" }, commandCtx);

    expectErr(result, CoNotFoundError);
  });

  it("returns error when change order is not in SUBMITTED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePurchaseChangeOrder); // DRAFT

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

    expectErr(result, CoNotSubmittedError);
  });

  it("returns error when change order is already APPROVED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(approvedChangeOrder);

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

    expectErr(result, CoNotSubmittedError);
  });
});
