import type { DB } from "../generated/kysely-tailordb";
import { decodeJson, summarizeOrderProgress, type PurchaseOrderLineInput } from "../lib/domain";
import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/module";

export type GetPurchaseOrderInput =
  | { id: string }
  | { companyId: string; externalSupplierOrderReference: string };

export async function run(db: ReadonlyDB<DB>, input: GetPurchaseOrderInput) {
  let query = db.selectFrom("PurchaseOrder").selectAll();
  if ("id" in input) {
    query = query.where("id", "=", input.id);
  } else {
    query = query
      .where("companyId", "=", input.companyId)
      .where("externalSupplierOrderReference", "=", input.externalSupplierOrderReference);
  }

  const purchaseOrder = await query.executeTakeFirst();
  if (!purchaseOrder) {
    return ok({ purchaseOrder: null });
  }

  const lines = decodeJson<PurchaseOrderLineInput[]>(purchaseOrder.lines, []);
  return ok({
    purchaseOrder: {
      ...purchaseOrder,
      lines,
      paymentTermSnapshot: decodeJson(purchaseOrder.paymentTermSnapshot, null),
      fulfillmentTotals: summarizeOrderProgress(lines),
    },
  });
}
