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

export interface ListPurchaseOrderLinesForMatchingInput {
  purchaseOrderLineIds: string[];
}

export interface PurchaseOrderLineForMatching {
  id: string;
  purchaseOrderId: string;
  quantity: string;
  unitPrice: string;
  unitId: string;
  requiresPhysicalReceipt: boolean;
}

export async function run(db: ReadonlyDB<DB>, input: ListPurchaseOrderLinesForMatchingInput) {
  if (input.purchaseOrderLineIds.length === 0) {
    return ok({ purchaseOrderLines: [] as PurchaseOrderLineForMatching[] });
  }

  const purchaseOrderLines = await db
    .selectFrom("PurchaseOrderLine")
    .select(["id", "purchaseOrderId", "quantity", "unitPrice", "unitId", "requiresPhysicalReceipt"])
    .where("id", "in", input.purchaseOrderLineIds)
    .execute();

  return ok({ purchaseOrderLines });
}
