import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  EmptyPurchaseOrderLinesError,
  PartnerNotSupplierError,
  PurchaseOrderNotDraftError,
  PurchaseOrderNotFoundError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { basePurchaseOrder, basePurchaseOrderLine, baseSupplierRole } from "../testing/fixtures";
import { mockBPQueries } from "../testing/moduleMocks";
import { run } from "./submitPurchaseOrder";

describe("submitPurchaseOrder", () => {
  it("submits a valid draft purchase order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const line = { ...basePurchaseOrderLine, purchaseOrderId: basePurchaseOrder.id };
    const bpQ = mockBPQueries({ partnerRole: baseSupplierRole });
    mock.enqueueResults(
      [basePurchaseOrder], // selectFrom PurchaseOrder
      [line], // selectFrom PurchaseOrderLine (execute → array)
      [{ ...basePurchaseOrder, orderStatus: "SUBMITTED" }], // update PurchaseOrder
    );

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

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

  it("returns error when purchase order does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: "missing-order" }, commandCtx, mockBPQueries()),
    );

    expectErr(result, PurchaseOrderNotFoundError);
  });

  it("returns error when purchase order is not in draft", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...basePurchaseOrder, orderStatus: "SUBMITTED" }]);

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

    expectErr(result, PurchaseOrderNotDraftError);
  });

  it("returns error when purchase order has no lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [basePurchaseOrder], // selectFrom PurchaseOrder
      [], // selectFrom PurchaseOrderLine (execute → empty array)
    );

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

    expectErr(result, EmptyPurchaseOrderLinesError);
  });

  it("returns error when supplier is no longer classified as a supplier", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const line = { ...basePurchaseOrderLine, purchaseOrderId: basePurchaseOrder.id };
    const bpQ = mockBPQueries();
    mock.enqueueResults(
      [basePurchaseOrder], // selectFrom PurchaseOrder
      [line], // selectFrom PurchaseOrderLine (execute → array)
    );

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

    expectErr(result, PartnerNotSupplierError);
  });

  it("submits when line has requiresPhysicalReceipt false and no receiving site", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const lineNoReceipt = {
      ...basePurchaseOrderLine,
      purchaseOrderId: basePurchaseOrder.id,
      requiresPhysicalReceipt: false,
      receivingSiteId: null,
    };
    const bpQ = mockBPQueries({ partnerRole: baseSupplierRole });
    mock.enqueueResults(
      [basePurchaseOrder], // selectFrom PurchaseOrder
      [lineNoReceipt], // selectFrom PurchaseOrderLine
      [{ ...basePurchaseOrder, orderStatus: "SUBMITTED" }], // update PurchaseOrder
    );

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

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