/* eslint-disable @typescript-eslint/array-type */
import type { DB } from "../generated/kysely-tailordb";
import { decodeJson } from "../lib/domain";
import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/module";

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 });
  }

  return ok({
    goodsReceipt: {
      ...goodsReceipt,
      lines: decodeJson(goodsReceipt.lines, [] as Array<Record<string, unknown>>),
      inventoryHandoff: decodeJson(goodsReceipt.inventoryHandoff, null),
    },
  });
}
