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

export interface GetBillOfMaterialInput {
  id: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetBillOfMaterialInput) {
  const billOfMaterial = await db
    .selectFrom("BillOfMaterial")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!billOfMaterial) {
    return err(new BomNotFoundError(input.id));
  }

  const lines = await db
    .selectFrom("BillOfMaterialLine")
    .selectAll()
    .where("billOfMaterialId", "=", billOfMaterial.id)
    .execute();

  return ok({ billOfMaterial, lines });
}
