import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ItemNotActiveError,
  MissingCommercialSnapshotError,
  PartnerNotSupplierError,
  PurchaseOrderNotFoundError,
  PurchaseOrderNotSubmittedError,
  SupplierNotActiveError,
} from "../lib/errors.generated";
import {
  baseItem,
  basePaymentTerm,
  basePurchaseOrder,
  submittedPurchaseOrder,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./approvePurchaseOrder";

describe("approvePurchaseOrder", () => {
  it("approves a valid submitted purchase order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(submittedPurchaseOrder)
      .mockReturnValueOnce({ id: submittedPurchaseOrder.supplierId, status: "ACTIVE" })
      .mockReturnValueOnce({ role: "SUPPLIER" })
      .mockReturnValueOnce(baseItem);
    spies.update.mockReturnValueOnce({ ...submittedPurchaseOrder, status: "ORDERED" });

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

    expect(expectOk(result).purchaseOrder.status).toBe("ORDERED");
  });

  it("freezes payment-term snapshot at approval time", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const orderWithoutSnapshot = {
      ...submittedPurchaseOrder,
      paymentTermSnapshot: null,
      paymentTermId: basePaymentTerm.id,
    };
    spies.select
      .mockReturnValueOnce(orderWithoutSnapshot)
      .mockReturnValueOnce({ id: orderWithoutSnapshot.supplierId, status: "ACTIVE" })
      .mockReturnValueOnce({ role: "SUPPLIER" })
      .mockReturnValueOnce(basePaymentTerm)
      .mockReturnValueOnce(baseItem);
    spies.update.mockReturnValueOnce({ ...orderWithoutSnapshot, status: "ORDERED" });

    await run(db, { id: orderWithoutSnapshot.id }, commandCtx);

    const setCall = spies.set.mock.calls[0]?.[0] as { paymentTermSnapshot?: string };
    expect(setCall.paymentTermSnapshot).toEqual(expect.any(String));
  });

  it("freezes ordered line prices and matched rule references at approval time", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const orderWithoutSnapshots = {
      ...submittedPurchaseOrder,
      lines: JSON.stringify([
        {
          id: "po-line-1",
          itemId: baseItem.id,
          quantity: 10,
          unitPrice: 100,
          unitId: "unit-1",
          receivingSiteId: "site-1",
          requiresPhysicalReceipt: true,
          matchedPriceRuleId: "price-rule-1",
          priceSnapshot: null,
          receivedQuantity: 0,
          billedQuantity: 0,
        },
      ]),
    };
    spies.select
      .mockReturnValueOnce(orderWithoutSnapshots)
      .mockReturnValueOnce({ id: orderWithoutSnapshots.supplierId, status: "ACTIVE" })
      .mockReturnValueOnce({ role: "SUPPLIER" })
      .mockReturnValueOnce(baseItem);
    spies.update.mockReturnValueOnce({ ...orderWithoutSnapshots, status: "ORDERED" });

    await run(db, { id: orderWithoutSnapshots.id }, commandCtx);

    const setCall = spies.set.mock.calls[0]?.[0] as { lines?: string };
    expect(setCall.lines).toContain('"priceSnapshot"');
  });

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

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

    expectErr(result, PurchaseOrderNotFoundError);
  });

  it("returns error when purchase order is not submitted", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePurchaseOrder);

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

    expectErr(result, PurchaseOrderNotSubmittedError);
  });

  it("returns error when supplier is inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(submittedPurchaseOrder)
      .mockReturnValueOnce({ id: submittedPurchaseOrder.supplierId, status: "INACTIVE" });

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

    expectErr(result, SupplierNotActiveError);
  });

  it("returns error when an item is inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(submittedPurchaseOrder)
      .mockReturnValueOnce({ id: submittedPurchaseOrder.supplierId, status: "ACTIVE" })
      .mockReturnValueOnce({ role: "SUPPLIER" })
      .mockReturnValueOnce({ ...baseItem, status: "INACTIVE" });

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

    expectErr(result, ItemNotActiveError);
  });

  it("returns error when supplier is no longer classified as a supplier", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(submittedPurchaseOrder)
      .mockReturnValueOnce({ id: submittedPurchaseOrder.supplierId, status: "ACTIVE" })
      .mockReturnValueOnce(undefined);

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

    expectErr(result, PartnerNotSupplierError);
  });

  it("returns error when approval cannot reconstruct the commercial snapshot", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const orderWithoutSnapshot = {
      ...submittedPurchaseOrder,
      paymentTermSnapshot: null,
      paymentTermId: basePaymentTerm.id,
    };
    spies.select
      .mockReturnValueOnce(orderWithoutSnapshot)
      .mockReturnValueOnce({ id: orderWithoutSnapshot.supplierId, status: "ACTIVE" })
      .mockReturnValueOnce({ role: "SUPPLIER" })
      .mockReturnValueOnce(undefined);

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

    expectErr(result, MissingCommercialSnapshotError);
  });
});
