import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import { Decimal } from "decimal.js";
import type { DB } from "../generated/kysely-tailordb";

export type GetPurchaseOrderInput = { id: string };

export async function run(db: ReadonlyDB<DB>, input: GetPurchaseOrderInput) {
  const id = input.id;

  const purchaseOrder = await db
    .selectFrom("PurchaseOrder")
    .selectAll()
    .where("id", "=", id)
    .executeTakeFirst();
  if (!purchaseOrder) return ok({ purchaseOrder: null });

  const lines = await db
    .selectFrom("PurchaseOrderLine")
    .selectAll()
    .where("purchaseOrderId", "=", id)
    .execute();

  // Direct per-line quantities (no lineage resolution)
  const enrichedLines = lines.map((line) => {
    const billedQuantity = new Decimal(line.billedQuantity ?? "0");
    const qty = new Decimal(line.quantity);
    return {
      ...line,
      billedQuantity: billedQuantity.toString(),
      remainingQuantityToBill: Decimal.max(qty.minus(billedQuantity), 0).toString(),
    };
  });

  return ok({
    purchaseOrder: {
      ...purchaseOrder,
      lines: enrichedLines,
    },
  });
}
