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

const builtins = (params: { companyType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "salesPaymentTerms",
        })
      : companyId,
    name: db.string().description("Payment-term name"),
    code: db.string({ optional: true }).description("Optional payment-term code"),
    status: db.enum(salesPaymentTermLifecycle.states).description("Payment-term lifecycle status"),
    scheduleLines: db.string().description("Serialized schedule lines"),
    notes: db.string({ optional: true }).description("Optional notes"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

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

export const salesPaymentTerm = createSalesPaymentTermType({});
