import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField } from "@tailor-platform/sdk";
import { accountPayableDocument } from "./accountPayableDocument";

const builtins = {
  accountPayableDocumentId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: accountPayableDocument },
      backward: "dueScheduleLines",
    })
    .description("Foreign key to AccountPayableDocument"),
  dueDate: db.date().description("Date when this payable installment is due"),
  amount: db.decimal().description("Positive due amount in transaction currency"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

export interface CreateAccountPayableDueScheduleLineTypeParams<
  F extends Record<string, TailorAnyDBField>,
> {
  fields?: NoReservedFields<F, ReservedFields>;
}

export function createAccountPayableDueScheduleLineType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateAccountPayableDueScheduleLineTypeParams<F> = {}) {
  return db
    .type("AccountPayableDueScheduleLine", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const accountPayableDueScheduleLine = createAccountPayableDueScheduleLineType();
