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

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

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

export function createPurchasePaymentTermType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchasePaymentTermTypeParams<F>,
) {
  return db
    .type("PurchasePaymentTerm", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "purchasePaymentTerms",
        })
        .description("Foreign key to Company"),
      name: db.string().description("Payment-term display name"),
      code: db.string({ optional: true }).description("Optional payment-term code"),
      status: db
        .enum(PURCHASE_PAYMENT_TERM_STATUSES)
        .description("Lifecycle status: ACTIVE, INACTIVE"),
      scheduleLines: db
        .string()
        .description("Serialized schedule-line definition for payable scheduling"),
      notes: db.string({ optional: true }).description("Optional descriptive notes"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const purchasePaymentTerm = createPurchasePaymentTermType({});
