import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { company as companyStub } from "../lib/_db_deps";

export const SALES_PAYMENT_TERM_STATUSES: [string, string, string] = [
  "DRAFT",
  "ACTIVE",
  "INACTIVE",
];

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(SALES_PAYMENT_TERM_STATUSES).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(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const salesPaymentTerm = createSalesPaymentTermType({});
