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

const builtins = (params: { companyType?: TailorAnyDBType; supplierType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  const supplierId = db.uuid().description("Foreign key to supplier BusinessPartner");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "invoiceToleranceConfigs",
        })
      : companyId,
    supplierId: params.supplierType
      ? supplierId.relation({
          type: "n-1",
          toward: { type: params.supplierType },
          backward: "invoiceToleranceConfigs",
        })
      : supplierId,
    quantityAbsoluteTolerance: db
      .decimal({ optional: true })
      .description("Optional absolute quantity tolerance for AP invoice checks"),
    quantityPercentageTolerance: db
      .decimal({ optional: true })
      .description("Optional percentage quantity tolerance for AP invoice checks; 0.05 means 5%"),
    unitPriceAbsoluteTolerance: db
      .decimal({ optional: true })
      .description("Optional absolute unit price tolerance for AP invoice checks"),
    unitPricePercentageTolerance: db
      .decimal({ optional: true })
      .description("Optional percentage unit price tolerance for AP invoice checks; 0.05 means 5%"),
  };
};

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

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

export function createInvoiceToleranceConfigType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateInvoiceToleranceConfigTypeParams<F>,
) {
  return db
    .type("InvoiceToleranceConfig", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["companyId", "supplierId"],
      unique: true,
      name: "invoice_tolerance_company_supplier_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const invoiceToleranceConfig = createInvoiceToleranceConfigType({});
