/* 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 GetPurchasePaymentTermInput {
  id: string;
}

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

  if (!purchasePaymentTerm) {
    return ok({ purchasePaymentTerm: null });
  }

  return ok({
    purchasePaymentTerm: {
      ...purchasePaymentTerm,
      scheduleLines: decodeJson(
        purchasePaymentTerm.scheduleLines,
        [] as Array<Record<string, unknown>>,
      ),
    },
  });
}
