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

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, lines: [] });
  }

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

  return ok({
    purchasePaymentTerm,
    lines,
  });
}
