import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  DuplicateExternalSupplierOrderReferenceError,
  EmptyPurchaseOrderLinesError,
  PartnerNotSupplierError,
  PurchaseOrderNotDraftError,
  PurchaseOrderNotFoundError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk, mockBPQueries } from "../testing/commandTestUtils";
import { basePurchaseOrder, basePurchaseOrderLine } from "../testing/fixtures";
import { run } from "./submitPurchaseOrder";

describe("submitPurchaseOrder", () => {
  it("submits a valid draft purchase order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const line = { ...basePurchaseOrderLine, purchaseOrderId: basePurchaseOrder.id };
    const bpQ = mockBPQueries({ partnerRole: { role: "SUPPLIER" } });
    spies.select
      .mockReturnValueOnce(basePurchaseOrder) // selectFrom PurchaseOrder
      .mockReturnValueOnce([line]) // selectFrom PurchaseOrderLine (execute → array)
      .mockReturnValueOnce(undefined); // findPurchaseOrderByExternalReference
    spies.update.mockReturnValueOnce({ ...basePurchaseOrder, orderStatus: "SUBMITTED" });

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

    expect(expectOk(result).purchaseOrder.orderStatus).toBe("SUBMITTED");
  });

  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, mockBPQueries());

    expectErr(result, PurchaseOrderNotFoundError);
  });

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

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

    expectErr(result, PurchaseOrderNotDraftError);
  });

  it("returns error when purchase order has no lines", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePurchaseOrder) // selectFrom PurchaseOrder
      .mockReturnValueOnce([]); // selectFrom PurchaseOrderLine (execute → empty array)

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

    expectErr(result, EmptyPurchaseOrderLinesError);
  });

  it("returns error when supplier is no longer classified as a supplier", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const line = { ...basePurchaseOrderLine, purchaseOrderId: basePurchaseOrder.id };
    const bpQ = mockBPQueries({ partnerRole: undefined });
    spies.select
      .mockReturnValueOnce(basePurchaseOrder) // selectFrom PurchaseOrder
      .mockReturnValueOnce([line]); // selectFrom PurchaseOrderLine (execute → array)

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

    expectErr(result, PartnerNotSupplierError);
  });

  it("submits when line has requiresPhysicalReceipt false and no receiving site", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const lineNoReceipt = {
      ...basePurchaseOrderLine,
      purchaseOrderId: basePurchaseOrder.id,
      requiresPhysicalReceipt: false,
      receivingSiteId: null,
    };
    const bpQ = mockBPQueries({ partnerRole: { role: "SUPPLIER" } });
    spies.select
      .mockReturnValueOnce(basePurchaseOrder) // selectFrom PurchaseOrder
      .mockReturnValueOnce([lineNoReceipt]) // selectFrom PurchaseOrderLine
      .mockReturnValueOnce(undefined); // findPurchaseOrderByExternalReference
    spies.update.mockReturnValueOnce({ ...basePurchaseOrder, orderStatus: "SUBMITTED" });

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

    expect(expectOk(result).purchaseOrder.orderStatus).toBe("SUBMITTED");
  });

  it("returns error when external supplier order reference is duplicated", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const line = { ...basePurchaseOrderLine, purchaseOrderId: basePurchaseOrder.id };
    const bpQ = mockBPQueries({ partnerRole: { role: "SUPPLIER" } });
    spies.select
      .mockReturnValueOnce(basePurchaseOrder) // selectFrom PurchaseOrder
      .mockReturnValueOnce([line]) // selectFrom PurchaseOrderLine (execute → array)
      .mockReturnValueOnce({ id: "duplicate-order" }); // findPurchaseOrderByExternalReference

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

    expectErr(result, DuplicateExternalSupplierOrderReferenceError);
  });
});
