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

export interface GetSalesPaymentTermInput {
  id: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetSalesPaymentTermInput) {
  const salesPaymentTerm = await db
    .selectFrom("SalesPaymentTerm")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();
  if (!salesPaymentTerm) {
    return ok({ salesPaymentTerm: null });
  }
  return ok({
    salesPaymentTerm: {
      ...salesPaymentTerm,
      scheduleLines: decodeJson<PaymentTermScheduleLineInput[]>(salesPaymentTerm.scheduleLines, []),
    },
  });
}
