/* 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 type GetPurchaseBillInput =
  | { id: string }
  | { companyId: string; supplierId: string; invoiceNumber: string };

export async function run(db: ReadonlyDB<DB>, input: GetPurchaseBillInput) {
  let query = db.selectFrom("PurchaseBill").selectAll();
  if ("id" in input) {
    query = query.where("id", "=", input.id);
  } else {
    query = query
      .where("companyId", "=", input.companyId)
      .where("supplierId", "=", input.supplierId)
      .where("invoiceNumber", "=", input.invoiceNumber);
  }

  const purchaseBill = await query.executeTakeFirst();
  if (!purchaseBill) {
    return ok({ purchaseBill: null });
  }

  return ok({
    purchaseBill: {
      ...purchaseBill,
      lines: decodeJson(purchaseBill.lines, [] as Array<Record<string, unknown>>),
      paymentTermSnapshot: decodeJson(purchaseBill.paymentTermSnapshot, null),
      dueSchedule: decodeJson(purchaseBill.dueSchedule, null),
      comparisonEvidence: decodeJson(purchaseBill.comparisonEvidence, null),
    },
  });
}
