import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { company as companyStub } from "../lib/_db_deps";
import { salesPaymentTermLifecycle } from "./salesPaymentTerm.lifecycle.generated";

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

export function createSalesPaymentTermType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSalesPaymentTermTypeParams<F>,
) {
  return db
    .type("SalesPaymentTerm", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "salesPaymentTerms",
        })
        .description("Foreign key to Company"),
      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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const salesPaymentTerm = createSalesPaymentTermType({});
