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

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

export function createSupplierProfileType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSupplierProfileTypeParams<F>,
) {
  return db
    .type("SupplierProfile", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "supplierProfiles",
        })
        .description("Foreign key to Company"),
      supplierId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.supplierType ?? businessPartnerStub },
          backward: "supplierProfiles",
        })
        .description("Foreign key to supplier BusinessPartner"),
      defaultPurchasePaymentTermId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.paymentTermType ?? purchasePaymentTerm },
          backward: "supplierProfiles",
        })
        .description("Optional default PurchasePaymentTerm"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["companyId", "supplierId"],
      unique: true,
      name: "supplier_profile_company_supplier_unique_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const supplierProfile = createSupplierProfileType({});
