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

export interface GetGoodsReceiptInput {
  id: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetGoodsReceiptInput) {
  const goodsReceipt = await db
    .selectFrom("GoodsReceipt")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();
  if (!goodsReceipt) return ok({ goodsReceipt: null });

  const lines = await db
    .selectFrom("GoodsReceiptLine")
    .selectAll()
    .where("goodsReceiptId", "=", input.id)
    .execute();

  return ok({
    goodsReceipt: {
      ...goodsReceipt,
      lines,
    },
  });
}
