import type { EntityManager } from '../EntityManager.js';
import type {
  ColumnType,
  PropertyOptions,
  ReferenceOptions,
  EnumOptions,
  EmbeddedOptions,
  ManyToOneOptions,
  OneToManyOptions,
  OneToOneOptions,
  ManyToManyOptions,
} from '../metadata/types.js';
import type {
  AnyString,
  GeneratedColumnCallback,
  Constructor,
  CheckCallback,
  FilterQuery,
  EntityName,
  Dictionary,
  EntityMetadata,
  PrimaryKeyProp,
  EntityRepositoryType,
  Hidden,
  Opt,
  Primary,
  EntityClass,
  EntitySchemaWithMeta,
  InferEntity,
  MaybeReturnType,
  Ref,
  IndexCallback,
  FormulaCallback,
  EntityCtor,
  IsNever,
  IWrappedEntity,
  DefineConfig,
  Config,
} from '../typings.js';
import type { Raw } from '../utils/RawQueryFragment.js';
import type { ScalarReference } from './Reference.js';
import type { SerializeOptions } from '../serialization/EntitySerializer.js';
import type {
  Cascade,
  DeferMode,
  EmbeddedPrefixMode,
  LoadStrategy,
  QueryOrderKeysFlat,
  QueryOrderMap,
} from '../enums.js';
import type { EventSubscriber } from '../events/EventSubscriber.js';
import type { IType, Type } from '../types/Type.js';
import { types } from '../types/index.js';
import type { Collection } from './Collection.js';
import type { FilterOptions } from '../drivers/IDatabaseDriver.js';
/** Union of all option keys supported across all property definition types (scalar, enum, embedded, relations). */
export type UniversalPropertyKeys =
  | keyof PropertyOptions<any>
  | keyof EnumOptions<any>
  | keyof EmbeddedOptions<any, any>
  | keyof ReferenceOptions<any, any>
  | keyof ManyToOneOptions<any, any>
  | keyof OneToManyOptions<any, any>
  | keyof OneToOneOptions<any, any>
  | keyof ManyToManyOptions<any, any>;
type BuilderExtraKeys = '~options' | '~type' | '$type';
type ExcludeKeys = 'entity' | 'items';
type BuilderKeys = Exclude<UniversalPropertyKeys, ExcludeKeys> | BuilderExtraKeys;
type IncludeKeysForProperty = Exclude<keyof PropertyOptions<any>, ExcludeKeys> | BuilderExtraKeys;
type IncludeKeysForEnumOptions = Exclude<keyof EnumOptions<any>, ExcludeKeys> | BuilderExtraKeys;
type IncludeKeysForOneToManyOptions = Exclude<keyof OneToManyOptions<any, any>, ExcludeKeys> | BuilderExtraKeys;
type HasKind<Options, K extends string> = Options extends {
  kind: infer X extends string;
}
  ? X extends K
    ? true
    : false
  : false;
/** Lightweight chain result type for property builders - reduces type instantiation cost by avoiding full class resolution. */
export interface PropertyChain<Value, Options> {
  '~type'?: {
    value: Value;
  };
  '~options': Options;
  $type<T>(): PropertyChain<T, Options>;
  $type<Runtime, Raw, Serialized = Raw>(): PropertyChain<IType<Runtime, Raw, Serialized>, Options>;
  nullable(): PropertyChain<
    Value,
    Omit<Options, 'nullable'> & {
      nullable: true;
    }
  >;
  ref(): PropertyChain<
    Value,
    Omit<Options, 'ref'> & {
      ref: true;
    }
  >;
  primary(): PropertyChain<
    Value,
    Omit<Options, 'primary'> & {
      primary: true;
    }
  >;
  hidden(): PropertyChain<
    Value,
    Omit<Options, 'hidden'> & {
      hidden: true;
    }
  >;
  autoincrement(): PropertyChain<
    Value,
    Omit<Options, 'autoincrement'> & {
      autoincrement: true;
    }
  >;
  autoincrement(autoincrement: false): PropertyChain<
    Value,
    Omit<Options, 'autoincrement'> & {
      autoincrement: false;
    }
  >;
  persist(): PropertyChain<
    Value,
    Omit<Options, 'persist'> & {
      persist: true;
    }
  >;
  persist(persist: false): PropertyChain<
    Value,
    Omit<Options, 'persist'> & {
      persist: false;
    }
  >;
  version(): PropertyChain<
    Value,
    Omit<Options, 'version'> & {
      version: true;
    }
  >;
  lazy(): PropertyChain<Value, Options>;
  name<T extends string>(
    name: T,
  ): PropertyChain<
    Value,
    Omit<Options, 'fieldName'> & {
      fieldName: T;
    }
  >;
  fieldName<T extends string>(
    fieldName: T,
  ): PropertyChain<
    Value,
    Omit<Options, 'fieldName'> & {
      fieldName: T;
    }
  >;
  onCreate(onCreate: (entity: any, em: EntityManager) => Value): PropertyChain<
    Value,
    Options & {
      onCreate: (...args: any[]) => any;
    }
  >;
  default(defaultValue: string | string[] | number | number[] | boolean | null | Date | Raw): PropertyChain<
    Value,
    Omit<Options, 'default'> & {
      default: any;
    }
  >;
  defaultRaw(defaultRaw: string): PropertyChain<
    Value,
    Options & {
      defaultRaw: string;
    }
  >;
  formula(formula: string | FormulaCallback<any>): PropertyChain<
    Value,
    Omit<Options, 'formula'> & {
      formula: any;
    }
  >;
  onUpdate(onUpdate: (entity: any, em: EntityManager) => Value): PropertyChain<Value, Options>;
  fieldNames(...fieldNames: string[]): PropertyChain<Value, Options>;
  type(type: PropertyValueType): PropertyChain<Value, Options>;
  runtimeType(runtimeType: string): PropertyChain<Value, Options>;
  columnType(columnType: ColumnType | AnyString): PropertyChain<Value, Options>;
  columnTypes(...columnTypes: (ColumnType | AnyString)[]): PropertyChain<Value, Options>;
  length(length: number): PropertyChain<Value, Options>;
  precision(precision: number): PropertyChain<Value, Options>;
  scale(scale: number): PropertyChain<Value, Options>;
  returning(returning?: boolean): PropertyChain<Value, Options>;
  unsigned(unsigned?: boolean): PropertyChain<Value, Options>;
  hydrate(hydrate?: boolean): PropertyChain<Value, Options>;
  concurrencyCheck(concurrencyCheck?: boolean): PropertyChain<Value, Options>;
  generated(generated: string | GeneratedColumnCallback<any>): PropertyChain<Value, Options>;
  check(check: string | CheckCallback<any>): PropertyChain<Value, Options>;
  setter(setter?: boolean): PropertyChain<Value, Options>;
  getter(getter?: boolean): PropertyChain<Value, Options>;
  getterName(getterName: string): PropertyChain<Value, Options>;
  serializedPrimaryKey(serializedPrimaryKey?: boolean): PropertyChain<Value, Options>;
  serializer(serializer: (value: Value, options?: SerializeOptions<any>) => any): PropertyChain<Value, Options>;
  serializedName(serializedName: string): PropertyChain<Value, Options>;
  groups(...groups: string[]): PropertyChain<Value, Options>;
  customOrder(...customOrder: string[] | number[] | boolean[]): PropertyChain<Value, Options>;
  extra(extra: string): PropertyChain<Value, Options>;
  ignoreSchemaChanges(...ignoreSchemaChanges: ('type' | 'extra' | 'default')[]): PropertyChain<Value, Options>;
  index(index?: boolean | string): PropertyChain<Value, Options>;
  unique(unique?: boolean | string): PropertyChain<Value, Options>;
  comment(comment: string): PropertyChain<Value, Options>;
  accessor(accessor?: string | boolean): PropertyChain<Value, Options>;
  eager(
    eager?: boolean,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  cascade(
    ...cascade: Cascade[]
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  strategy(
    strategy: LoadStrategy | `${LoadStrategy}`,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  filters(
    filters: FilterOptions,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  mappedBy(
    mappedBy: (keyof Value & string) | ((e: Value) => any),
  ): HasKind<Options, '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  inversedBy(
    inversedBy: (keyof Value & string) | ((e: Value) => any),
  ): HasKind<Options, 'm:1' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  owner(): HasKind<Options, '1:1' | 'm:n'> extends true
    ? PropertyChain<
        Value,
        Omit<Options, 'owner'> & {
          owner: true;
        }
      >
    : never;
  mapToPk(): HasKind<Options, 'm:1' | '1:1'> extends true
    ? PropertyChain<
        Value,
        Omit<Options, 'mapToPk'> & {
          mapToPk: true;
        }
      >
    : never;
  orphanRemoval(
    orphanRemoval?: boolean,
  ): HasKind<Options, '1:m' | '1:1'> extends true ? PropertyChain<Value, Options> : never;
  discriminator(
    discriminator: string,
  ): HasKind<Options, 'm:1' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  discriminatorMap(
    discriminatorMap: Dictionary<string>,
  ): HasKind<Options, 'm:1' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  pivotTable(pivotTable: string): HasKind<Options, 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  pivotEntity(
    pivotEntity: () => EntityName,
  ): HasKind<Options, 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  fixedOrder(fixedOrder?: boolean): HasKind<Options, 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  fixedOrderColumn(
    fixedOrderColumn: string,
  ): HasKind<Options, 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  array(): HasKind<Options, 'embedded' | 'enum'> extends true
    ? PropertyChain<
        Value,
        Omit<Options, 'array'> & {
          array: true;
        }
      >
    : never;
  prefix(prefix: string | boolean): HasKind<Options, 'embedded'> extends true ? PropertyChain<Value, Options> : never;
  prefixMode(
    prefixMode: EmbeddedPrefixMode,
  ): HasKind<Options, 'embedded'> extends true ? PropertyChain<Value, Options> : never;
  object(object?: boolean): HasKind<Options, 'embedded'> extends true ? PropertyChain<Value, Options> : never;
  nativeEnumName(nativeEnumName: string): HasKind<Options, 'enum'> extends true ? PropertyChain<Value, Options> : never;
  orderBy(
    ...orderBy: QueryOrderMap<object>[]
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  where(
    ...where: FilterQuery<object>[]
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  joinColumn(
    joinColumn: string,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  joinColumns(
    ...joinColumns: string[]
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  inverseJoinColumn(
    inverseJoinColumn: string,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  inverseJoinColumns(
    ...inverseJoinColumns: string[]
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  referenceColumnName(
    referenceColumnName: string,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  referencedColumnNames(
    ...referencedColumnNames: string[]
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  ownColumns(
    ...ownColumns: string[]
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  targetKey(
    targetKey: keyof Value & string,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  deleteRule(
    deleteRule: 'cascade' | 'no action' | 'set null' | 'set default' | AnyString,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  updateRule(
    updateRule: 'cascade' | 'no action' | 'set null' | 'set default' | AnyString,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  deferMode(
    deferMode: DeferMode | `${DeferMode}`,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  createForeignKeyConstraint(
    createForeignKeyConstraint?: boolean,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
  foreignKeyName(
    foreignKeyName: string,
  ): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
}
/** @internal */
export declare class UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys extends BuilderKeys> implements Record<
  Exclude<UniversalPropertyKeys, ExcludeKeys>,
  any
> {
  '~options': Options;
  '~type'?: {
    value: Value;
  };
  constructor(options: any);
  protected assignOptions(options: EmptyOptions): any;
  /**
   * Set the TypeScript type of the property.
   */
  $type<T>(): UniversalPropertyOptionsBuilder<T, Options, IncludeKeys>;
  /**
   * Set the TypeScript type for custom types that map to objects.
   * This method provides type safety for custom types by specifying the runtime type,
   * raw database value type, and optional serialized type.
   *
   * @template Runtime - The runtime type that the property will have in JavaScript
   * @template Raw - The raw value type as stored in the database
   * @template Serialized - The type when serialized (defaults to Raw)
   * @returns PropertyOptionsBuilder with IType wrapper for type safety
   */
  $type<Runtime, Raw, Serialized = Raw>(): UniversalPropertyOptionsBuilder<
    IType<Runtime, Raw, Serialized>,
    Options,
    IncludeKeys
  >;
  /**
   * Alias for `fieldName`.
   */
  name<T extends string>(
    name: T,
  ): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'fieldName'> & {
        fieldName: T;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * Specify database column name for this property.
   *
   * @see https://mikro-orm.io/docs/naming-strategy
   */
  fieldName<T extends string>(
    fieldName: T,
  ): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'fieldName'> & {
        fieldName: T;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * Specify database column names for this property.
   * Same as `fieldName` but for composite FKs.
   *
   * @see https://mikro-orm.io/docs/naming-strategy
   */
  fieldNames(...fieldNames: string[]): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Specify an exact database column type for {@link https://mikro-orm.io/docs/schema-generator Schema Generator}. This option is only for simple properties represented by a single column. (SQL only)
   */
  columnType(
    columnType: ColumnType | AnyString,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Specify an exact database column type for {@link https://mikro-orm.io/docs/schema-generator Schema Generator}. This option is suitable for composite keys, where one property is represented by multiple columns. (SQL only)
   */
  columnTypes(
    ...columnTypes: (ColumnType | AnyString)[]
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Explicitly specify the runtime type.
   *
   * @see https://mikro-orm.io/docs/metadata-providers
   * @see https://mikro-orm.io/docs/custom-types
   */
  type<TType extends PropertyValueType>(
    type: TType,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Runtime type of the property. This is the JS type that your property is mapped to, e.g. `string` or `number`, and is normally inferred automatically via `reflect-metadata`.
   * In some cases, the inference won't work, and you might need to specify the `runtimeType` explicitly - the most common one is when you use a union type with null like `foo: number | null`.
   */
  runtimeType(runtimeType: string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set length of database column, used for datetime/timestamp/varchar column types for {@link https://mikro-orm.io/docs/schema-generator Schema Generator}. (SQL only)
   */
  length(length: number): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set precision of database column to represent the number of significant digits. (SQL only)
   */
  precision(precision: number): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set scale of database column to represents the number of digits after the decimal point. (SQL only)
   */
  scale(scale: number): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Explicitly specify the auto increment of the primary key.
   */
  autoincrement(): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'autoincrement'> & {
        autoincrement: true;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  autoincrement(autoincrement: false): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'autoincrement'> & {
        autoincrement: false;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * Add the property to the `returning` statement.
   */
  returning(returning?: boolean): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Automatically set the property value when entity gets created, executed during flush operation.
   */
  onCreate(onCreate: (entity: any, em: EntityManager) => Value): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Options & {
        onCreate: (...args: any[]) => any;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * Automatically update the property value every time entity gets updated, executed during flush operation.
   */
  onUpdate(
    onUpdate: (entity: any, em: EntityManager) => Value,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Specify default column value for {@link https://mikro-orm.io/docs/schema-generator Schema Generator}.
   * This is a runtime value, assignable to the entity property. (SQL only)
   */
  default<T extends string | string[] | number | number[] | boolean | null | Date | Raw>(
    defaultValue: T,
  ): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'default'> & {
        default: T;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * Specify SQL functions for {@link https://mikro-orm.io/docs/schema-generator Schema Generator}. (SQL only)
   * Since v4 you should use defaultRaw for SQL functions. e.g. now()
   */
  defaultRaw(defaultRaw: string): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Options & {
        defaultRaw: string;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * Allow controlling `filters` option. This will be overridden with `em.fork` or `FindOptions` if provided.
   */
  filters(filters: FilterOptions): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set to map some SQL snippet for the entity.
   *
   * @see https://mikro-orm.io/docs/defining-entities#formulas Formulas
   */
  formula<T extends string | FormulaCallback<any>>(
    formula: T,
  ): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'formula'> & {
        formula: T;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * For generated columns. This will be appended to the column type after the `generated always` clause.
   */
  generated(
    generated: string | GeneratedColumnCallback<any>,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set column as nullable for {@link https://mikro-orm.io/docs/schema-generator Schema Generator}.
   */
  nullable(): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'nullable'> & {
        nullable: true;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * Set column as unsigned for {@link https://mikro-orm.io/docs/schema-generator Schema Generator}. (SQL only)
   */
  unsigned(unsigned?: boolean): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set false to define {@link https://mikro-orm.io/docs/serializing#shadow-properties Shadow Property}.
   */
  persist(): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'persist'> & {
        persist: true;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  persist(persist: false): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'persist'> & {
        persist: false;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * Set false to disable hydration of this property. Useful for persisted getters.
   */
  hydrate(hydrate?: boolean): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Enable `ScalarReference` wrapper for lazy values. Use this in combination with `lazy: true` to have a type-safe accessor object in place of the value.
   */
  ref(): UniversalPropertyOptionsBuilder<
    Value,
    Omit<Options, 'ref'> & {
      ref: true;
    },
    IncludeKeys
  >;
  /**
   * Set to true to omit the property when {@link https://mikro-orm.io/docs/serializing Serializing}.
   */
  hidden(): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'hidden'> & {
        hidden: true;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * Set to true to enable {@link https://mikro-orm.io/docs/transactions#optimistic-locking Optimistic Locking} via version field. (SQL only)
   */
  version(): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'version'> & {
        version: true;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * Set to true to enable {@link https://mikro-orm.io/docs/transactions#optimistic-locking Optimistic Locking} via concurrency fields.
   */
  concurrencyCheck(
    concurrencyCheck?: boolean,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Explicitly specify index on a property.
   */
  index(index?: boolean | string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set column as unique for {@link https://mikro-orm.io/docs/schema-generator Schema Generator}. (SQL only)
   */
  unique(unique?: boolean | string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Specify column with check constraints. (Postgres driver only)
   *
   * @see https://mikro-orm.io/docs/defining-entities#check-constraints
   */
  check(
    check: string | CheckCallback<any>,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set to omit the property from the select clause for lazy loading.
   *
   * @see https://mikro-orm.io/docs/defining-entities#lazy-scalar-properties
   */
  lazy(): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set true to define entity's unique primary key identifier.
   *
   * @see https://mikro-orm.io/docs/decorators#primarykey
   */
  primary(): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'primary'> & {
        primary: true;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /**
   * Set true to define the properties as setter. (virtual)
   *
   * @example
   * ```
   * @Property({ setter: true })
   * set address(value: string) {
   *     this._address = value.toLocaleLowerCase();
   * }
   * ```
   */
  setter(setter?: boolean): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set true to define the properties as getter. (virtual)
   *
   * @example
   * ```
   * @Property({ getter: true })
   * get fullName() {
   *   return this.firstName + this.lastName;
   * }
   * ```
   */
  getter(getter?: boolean): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * When defining a property over a method (not a getter, a regular function), you can use this option to point
   * to the method name.
   *
   * @example
   * ```
   * @Property({ getter: true })
   * getFullName() {
   *   return this.firstName + this.lastName;
   * }
   * ```
   */
  getterName(getterName: string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set to define serialized primary key for MongoDB. (virtual)
   * Alias for `@SerializedPrimaryKey()` decorator.
   *
   * @see https://mikro-orm.io/docs/decorators#serializedprimarykey
   */
  serializedPrimaryKey(
    serializedPrimaryKey?: boolean,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set to use serialize property. Allow to specify a callback that will be used when serializing a property.
   *
   * @see https://mikro-orm.io/docs/serializing#property-serializers
   */
  serializer(
    serializer: (value: Value, options?: SerializeOptions<any>) => any,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Specify name of key for the serialized value.
   */
  serializedName(
    serializedName: string,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Specify serialization groups for `serialize()` calls. If a property does not specify any group, it will be included,
   * otherwise only properties with a matching group are included.
   */
  groups(...groups: string[]): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Specify a custom order based on the values. (SQL only)
   */
  customOrder(
    ...customOrder: string[] | number[] | boolean[]
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Specify comment of column for {@link https://mikro-orm.io/docs/schema-generator Schema Generator}. (SQL only)
   */
  comment(comment: string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** mysql only */
  extra(extra: string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /**
   * Set to avoid a perpetual diff from the {@link https://mikro-orm.io/docs/schema-generator Schema Generator} when columns are generated.
   *
   * @see https://mikro-orm.io/docs/defining-entities#sql-generated-columns
   */
  ignoreSchemaChanges(
    ...ignoreSchemaChanges: ('type' | 'extra' | 'default')[]
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  array(): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'array'> & {
        array: true;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /** for postgres, by default it uses text column with check constraint */
  nativeEnumName(
    nativeEnumName: string,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  prefix(prefix: string | boolean): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  prefixMode(
    prefixMode: EmbeddedPrefixMode,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  object(object?: boolean): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Set what actions on owning entity should be cascaded to the relationship. Defaults to [Cascade.PERSIST, Cascade.MERGE] (see {@doclink cascading}). */
  cascade(...cascade: Cascade[]): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Always load the relationship. Discouraged for use with to-many relations for performance reasons. */
  eager(eager?: boolean): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Override the default loading strategy for this property. This option has precedence over the global `loadStrategy`, but can be overridden by `FindOptions.strategy`. */
  strategy(
    strategy: LoadStrategy | `${LoadStrategy}`,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Set this side as owning. Owning side is where the foreign key is defined. This option is not required if you use `inversedBy` or `mappedBy` to distinguish owning and inverse side. */
  owner(): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'owner'> & {
        owner: true;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /** For polymorphic relations. Specifies the property name that stores the entity type discriminator. Defaults to the property name. */
  discriminator(discriminator: string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** For polymorphic relations. Custom mapping of discriminator values to entity class names. */
  discriminatorMap(
    discriminatorMap: Dictionary<string>,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Point to the inverse side property name. */
  inversedBy(
    inversedBy: keyof Value | ((e: Value) => any),
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Point to the owning side property name. */
  mappedBy(
    mappedBy: keyof Value | ((e: Value) => any),
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Condition for {@doclink collections#declarative-partial-loading | Declarative partial loading}. */
  where(
    ...where: FilterQuery<object>[]
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Set default ordering. */
  orderBy(
    ...orderBy: QueryOrderMap<object>[]
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Force stable insertion order of items in the collection (see {@doclink collections | Collections}). */
  fixedOrder(fixedOrder?: boolean): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Override default order column name (`id`) for fixed ordering. */
  fixedOrderColumn(
    fixedOrderColumn: string,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Override default name for pivot table (see {@doclink naming-strategy | Naming Strategy}). */
  pivotTable(pivotTable: string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Set pivot entity for this relation (see {@doclink collections#custom-pivot-table-entity | Custom pivot table entity}). */
  pivotEntity(
    pivotEntity: () => EntityName,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Override the default database column name on the owning side (see {@doclink naming-strategy | Naming Strategy}). This option is only for simple properties represented by a single column. */
  joinColumn(joinColumn: string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Override the default database column name on the owning side (see {@doclink naming-strategy | Naming Strategy}). This option is suitable for composite keys, where one property is represented by multiple columns. */
  joinColumns(
    ...joinColumns: string[]
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Override the default database column name on the inverse side (see {@doclink naming-strategy | Naming Strategy}). This option is only for simple properties represented by a single column. */
  inverseJoinColumn(
    inverseJoinColumn: string,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Override the default database column name on the inverse side (see {@doclink naming-strategy | Naming Strategy}). This option is suitable for composite keys, where one property is represented by multiple columns. */
  inverseJoinColumns(
    ...inverseJoinColumns: string[]
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Override the default database column name on the target entity (see {@doclink naming-strategy | Naming Strategy}). This option is only for simple properties represented by a single column. */
  referenceColumnName(
    referenceColumnName: string,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Override the default database column name on the target entity (see {@doclink naming-strategy | Naming Strategy}). This option is suitable for composite keys, where one property is represented by multiple columns. */
  referencedColumnNames(
    ...referencedColumnNames: string[]
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Specify the property name on the target entity that this FK references instead of the primary key. */
  targetKey(targetKey: keyof Value): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** What to do when the target entity gets deleted. */
  deleteRule(
    deleteRule: 'cascade' | 'no action' | 'set null' | 'set default' | AnyString,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** What to do when the reference to the target entity gets updated. */
  updateRule(
    updateRule: 'cascade' | 'no action' | 'set null' | 'set default' | AnyString,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Map this relation to the primary key value instead of an entity. */
  mapToPk(): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      Omit<Options, 'mapToPk'> & {
        mapToPk: true;
      },
      IncludeKeys
    >,
    IncludeKeys
  >;
  /** Set the constraint type. Immediate constraints are checked for each statement, while deferred ones are only checked at the end of the transaction. Only for postgres unique constraints. */
  deferMode(
    deferMode: DeferMode | `${DeferMode}`,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** When a part of a composite column is shared in other properties, use this option to specify what columns are considered as owned by this property. This is useful when your composite property is nullable, but parts of it are not. */
  ownColumns(...ownColumns: string[]): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Enable/disable foreign key constraint creation on this relation */
  createForeignKeyConstraint(
    createForeignKeyConstraint?: boolean,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Set a custom foreign key constraint name, overriding NamingStrategy.indexName(). */
  foreignKeyName(
    foreignKeyName: string,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  /** Remove the entity when it gets disconnected from the relationship (see {@doclink cascading | Cascading}). */
  orphanRemoval(
    orphanRemoval?: boolean,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
  accessor(
    accessor?: string | boolean,
  ): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
}
/** Empty options object used as the initial state for property builders. */
export interface EmptyOptions extends Partial<Record<UniversalPropertyKeys, unknown>> {}
/** @internal */
export declare class OneToManyOptionsBuilderOnlyMappedBy<Value extends object> extends UniversalPropertyOptionsBuilder<
  Value,
  EmptyOptions & {
    kind: '1:m';
  },
  IncludeKeysForOneToManyOptions
> {
  /** Point to the owning side property name. */
  mappedBy(mappedBy: keyof Value | ((e: Value) => any)): Pick<
    UniversalPropertyOptionsBuilder<
      Value,
      EmptyOptions & {
        kind: '1:m';
      },
      IncludeKeysForOneToManyOptions
    >,
    IncludeKeysForOneToManyOptions
  >;
}
type EntityTarget =
  | {
      '~entity': any;
    }
  | EntityClass;
declare const propertyBuilders: PropertyBuilders;
type PropertyBuildersOverrideKeys = 'bigint' | 'array' | 'decimal' | 'json' | 'datetime' | 'time' | 'enum';
/** Map of factory functions for creating type-safe property builders (scalars, enums, embeddables, and relations). */
export type PropertyBuilders = {
  [K in Exclude<keyof typeof types, PropertyBuildersOverrideKeys>]: () => UniversalPropertyOptionsBuilder<
    InferPropertyValueType<(typeof types)[K]>,
    EmptyOptions,
    IncludeKeysForProperty
  >;
} & {
  bigint: <Mode extends 'bigint' | 'number' | 'string' = 'bigint'>(
    mode?: Mode,
  ) => UniversalPropertyOptionsBuilder<
    InferPropertyValueType<typeof types.bigint<Mode>>,
    EmptyOptions,
    IncludeKeysForProperty
  >;
  array: <T = string>(
    toJsValue?: (i: string) => T,
    toDbValue?: (i: T) => string,
  ) => UniversalPropertyOptionsBuilder<
    InferPropertyValueType<typeof types.array<T>>,
    EmptyOptions,
    IncludeKeysForProperty
  >;
  decimal: <Mode extends 'number' | 'string' = 'string'>(
    mode?: Mode,
  ) => UniversalPropertyOptionsBuilder<
    InferPropertyValueType<typeof types.decimal<Mode>>,
    EmptyOptions,
    IncludeKeysForProperty
  >;
  json: <T>() => UniversalPropertyOptionsBuilder<T, EmptyOptions, IncludeKeysForProperty>;
  formula: <T>(
    formula: string | FormulaCallback<any>,
  ) => UniversalPropertyOptionsBuilder<T, EmptyOptions, IncludeKeysForProperty>;
  datetime: (
    length?: number,
  ) => UniversalPropertyOptionsBuilder<
    InferPropertyValueType<typeof types.datetime>,
    EmptyOptions,
    IncludeKeysForProperty
  >;
  time: (
    length?: number,
  ) => UniversalPropertyOptionsBuilder<InferPropertyValueType<typeof types.time>, EmptyOptions, IncludeKeysForProperty>;
  type: <T extends PropertyValueType>(
    type: T,
  ) => UniversalPropertyOptionsBuilder<InferPropertyValueType<T>, EmptyOptions, IncludeKeysForProperty>;
  enum: <const T extends (number | string)[] | (() => Dictionary)>(
    items?: T,
  ) => UniversalPropertyOptionsBuilder<
    T extends () => Dictionary ? ValueOf<ReturnType<T>> : T extends (infer Value)[] ? Value : T,
    EmptyOptions,
    IncludeKeysForEnumOptions
  >;
  embedded: <Target extends EntityTarget | EntityTarget[]>(
    target: Target,
  ) => PropertyChain<
    InferEntity<Target extends (infer T)[] ? T : Target>,
    EmptyOptions & {
      kind: 'embedded';
    }
  >;
  manyToMany: <Target extends EntityTarget>(
    target: Target,
  ) => PropertyChain<
    InferEntity<Target>,
    EmptyOptions & {
      kind: 'm:n';
    }
  >;
  manyToOne: <Target extends EntityTarget | EntityTarget[]>(
    target: Target,
  ) => PropertyChain<
    InferEntity<Target extends (infer T)[] ? T : Target>,
    EmptyOptions & {
      kind: 'm:1';
    }
  >;
  oneToMany: <Target extends EntityTarget>(
    target: Target,
  ) => PropertyChain<
    InferEntity<Target>,
    EmptyOptions & {
      kind: '1:m';
    }
  >;
  oneToOne: <Target extends EntityTarget | EntityTarget[]>(
    target: Target,
  ) => PropertyChain<
    InferEntity<Target extends (infer T)[] ? T : Target>,
    EmptyOptions & {
      kind: '1:1';
    }
  >;
};
/** Own keys + base entity keys (when TBase is not `never`). Guards against `keyof never = string | number | symbol`. */
type AllKeys<TProperties, TBase> = keyof TProperties | (IsNever<TBase> extends true ? never : keyof TBase);
/** Metadata descriptor for `defineEntity()`, combining entity options with property definitions. */
export interface EntityMetadataWithProperties<
  TName extends string,
  TTableName extends string,
  TProperties extends Record<string, any>,
  TPK extends (keyof TProperties)[] | undefined = undefined,
  TBase = never,
  TRepository = never,
  TForceObject extends boolean = false,
> extends Omit<
  Partial<EntityMetadata<InferEntityFromProperties<TProperties, TPK, TBase, TRepository>>>,
  | 'properties'
  | 'extends'
  | 'primaryKeys'
  | 'hooks'
  | 'discriminatorColumn'
  | 'versionProperty'
  | 'concurrencyCheckKeys'
  | 'serializedPrimaryKey'
  | 'indexes'
  | 'uniques'
  | 'repository'
  | 'orderBy'
> {
  name: TName;
  tableName?: TTableName;
  extends?:
    | {
        '~entity': TBase;
      }
    | EntityCtor<TBase>;
  properties: TProperties | ((properties: PropertyBuilders) => TProperties);
  primaryKeys?: TPK & InferPrimaryKey<TProperties>[];
  hooks?: DefineEntityHooks;
  repository?: () => TRepository;
  forceObject?: TForceObject;
  inheritance?: 'tpt';
  orderBy?:
    | {
        [K in Extract<AllKeys<TProperties, TBase>, string>]?: QueryOrderKeysFlat;
      }
    | {
        [K in Extract<AllKeys<TProperties, TBase>, string>]?: QueryOrderKeysFlat;
      }[];
  discriminatorColumn?: string;
  versionProperty?: AllKeys<TProperties, TBase>;
  concurrencyCheckKeys?: Set<AllKeys<TProperties, TBase>>;
  serializedPrimaryKey?: AllKeys<TProperties, TBase>;
  indexes?: {
    properties?: keyof TProperties | (keyof TProperties)[];
    name?: string;
    type?: string;
    options?: Dictionary;
    expression?: string | IndexCallback<InferEntityFromProperties<TProperties, TPK, TBase>>;
  }[];
  uniques?: {
    properties?: keyof TProperties | (keyof TProperties)[];
    name?: string;
    options?: Dictionary;
    expression?: string | IndexCallback<InferEntityFromProperties<TProperties, TPK, TBase>>;
    deferMode?: DeferMode | `${DeferMode}`;
  }[];
}
/** Defines an entity schema using property builders, with full type inference from the property definitions. */
export declare function defineEntity<
  const TName extends string,
  const TTableName extends string,
  const TProperties extends Record<string, any>,
  const TPK extends (keyof TProperties)[] | undefined = undefined,
  const TBase = never,
  const TRepository = never,
  const TForceObject extends boolean = false,
>(
  meta: EntityMetadataWithProperties<TName, TTableName, TProperties, TPK, TBase, TRepository, TForceObject>,
): EntitySchemaWithMeta<
  TName,
  TTableName,
  InferEntityFromProperties<TProperties, TPK, TBase, TRepository, TForceObject>,
  TBase,
  TProperties
>;
/** Defines an entity schema for an existing class, combining the class with property builders. */
export declare function defineEntity<
  const TEntity = any,
  const TProperties extends Record<string, any> = Record<string, any>,
  const TClassName extends string = string,
  const TTableName extends string = string,
  const TBase = never,
  const TClass extends EntityCtor = EntityCtor<TEntity>,
>(
  meta: Omit<Partial<EntityMetadata<TEntity>>, 'properties' | 'extends' | 'className' | 'tableName' | 'hooks'> & {
    class: TClass;
    className?: TClassName;
    tableName?: TTableName;
    extends?: TBase;
    properties: TProperties | ((properties: PropertyBuilders) => TProperties);
    hooks?: DefineEntityHooks<TEntity>;
  },
): EntitySchemaWithMeta<TClassName, TTableName, TEntity, TBase, TProperties, TClass>;
export declare namespace defineEntity {
  var properties: PropertyBuilders;
}
/** Shorthand alias for `defineEntity.properties` - the property builders for use in `defineEntity()`. */
export { propertyBuilders as p };
type EntityHookValue<T, K extends keyof EventSubscriber<T>> = (keyof T | NonNullable<EventSubscriber<T>[K]>)[];
/** Lifecycle hook definitions for entities created via `defineEntity()`. */
export interface DefineEntityHooks<T = any> {
  onInit?: EntityHookValue<T, 'onInit'>;
  onLoad?: EntityHookValue<T, 'onLoad'>;
  beforeCreate?: EntityHookValue<T, 'beforeCreate'>;
  afterCreate?: EntityHookValue<T, 'afterCreate'>;
  beforeUpdate?: EntityHookValue<T, 'beforeUpdate'>;
  afterUpdate?: EntityHookValue<T, 'afterUpdate'>;
  beforeUpsert?: EntityHookValue<T, 'beforeUpsert'>;
  afterUpsert?: EntityHookValue<T, 'afterUpsert'>;
  beforeDelete?: EntityHookValue<T, 'beforeDelete'>;
  afterDelete?: EntityHookValue<T, 'afterDelete'>;
}
type PropertyValueType = PropertyOptions<any>['type'];
type InferPropertyValueType<T extends PropertyValueType> = T extends string
  ? InferTypeByString<T>
  : T extends NumberConstructor
    ? number
    : T extends StringConstructor
      ? string
      : T extends BooleanConstructor
        ? boolean
        : T extends DateConstructor
          ? Date
          : T extends ArrayConstructor
            ? string[]
            : T extends Constructor<infer TType>
              ? TType extends Type<infer TValue, any>
                ? NonNullable<TValue>
                : TType
              : T extends Type<infer TValue, any>
                ? NonNullable<TValue>
                : any;
type InferTypeByString<T extends string> = T extends keyof typeof types
  ? InferJSType<(typeof types)[T]>
  : InferColumnType<T>;
type InferJSType<T> = T extends typeof Type<infer TValue, any> ? NonNullable<TValue> : never;
type InferColumnType<T extends string> = T extends
  | 'int'
  | 'int4'
  | 'integer'
  | 'bigint'
  | 'int8'
  | 'int2'
  | 'tinyint'
  | 'smallint'
  | 'mediumint'
  ? number
  : T extends 'double' | 'double precision' | 'real' | 'float8' | 'decimal' | 'numeric' | 'float' | 'float4'
    ? number
    : T extends
          | 'datetime'
          | 'time'
          | 'time with time zone'
          | 'timestamp'
          | 'timestamp with time zone'
          | 'timetz'
          | 'timestamptz'
          | 'date'
          | 'interval'
      ? Date
      : T extends
            | 'ObjectId'
            | 'objectId'
            | 'character varying'
            | 'varchar'
            | 'char'
            | 'character'
            | 'uuid'
            | 'text'
            | 'tinytext'
            | 'mediumtext'
            | 'longtext'
            | 'enum'
        ? string
        : T extends 'boolean' | 'bool' | 'bit'
          ? boolean
          : T extends 'blob' | 'tinyblob' | 'mediumblob' | 'longblob' | 'bytea'
            ? Buffer
            : T extends 'point' | 'line' | 'lseg' | 'box' | 'circle' | 'path' | 'polygon' | 'geometry'
              ? number[]
              : T extends 'tsvector' | 'tsquery'
                ? string[]
                : T extends 'json' | 'jsonb'
                  ? any
                  : any;
type BaseEntityMethodKeys = 'toObject' | 'toPOJO' | 'serialize' | 'assign' | 'populate' | 'init' | 'toReference';
/** Infers the entity type from a `defineEntity()` properties map, resolving builders, base classes, and primary keys. */
export type InferEntityFromProperties<
  Properties extends Record<string, any>,
  PK extends (keyof Properties)[] | undefined = undefined,
  Base = never,
  Repository = never,
  ForceObject extends boolean = false,
> = (IsNever<Base> extends true
  ? {}
  : Base extends {
        toObject(...args: any[]): any;
      }
    ? Pick<
        IWrappedEntity<
          {
            -readonly [K in keyof Properties]: InferBuilderValue<MaybeReturnType<Properties[K]>>;
          } & {
            [PrimaryKeyProp]?: InferCombinedPrimaryKey<Properties, PK, Base>;
          } & (IsNever<Repository> extends true
              ? {}
              : {
                  [EntityRepositoryType]?: Repository extends Constructor<infer R> ? R : Repository;
                }) &
            Omit<Base, typeof PrimaryKeyProp>
        >,
        BaseEntityMethodKeys
      >
    : {}) & {
  -readonly [K in keyof Properties]: InferBuilderValue<MaybeReturnType<Properties[K]>>;
} & {
  [PrimaryKeyProp]?: InferCombinedPrimaryKey<Properties, PK, Base>;
} & (IsNever<Repository> extends true
    ? {}
    : {
        [EntityRepositoryType]?: Repository extends Constructor<infer R> ? R : Repository;
      }) &
  (IsNever<Base> extends true ? {} : Omit<Base, typeof PrimaryKeyProp>) &
  (ForceObject extends true
    ? {
        [Config]?: DefineConfig<{
          forceObject: true;
        }>;
      }
    : {});
type InferCombinedPrimaryKey<Properties extends Record<string, any>, PK, Base> = PK extends undefined
  ? CombinePrimaryKeys<InferPrimaryKey<Properties>, ExtractBasePrimaryKey<Base>>
  : PK;
type ExtractBasePrimaryKey<Base> = Base extends {
  [PrimaryKeyProp]?: infer BasePK;
}
  ? BasePK
  : never;
type CombinePrimaryKeys<ChildPK, BasePK> = [ChildPK] extends [never]
  ? BasePK
  : [BasePK] extends [never]
    ? IsUnion<ChildPK> extends true
      ? ChildPK[]
      : ChildPK
    : ChildPK | BasePK;
/** Extracts the primary key property names from a properties map by finding builders with `primary: true`. */
export type InferPrimaryKey<Properties extends Record<string, any>> = {
  [K in keyof Properties]: MaybeReturnType<Properties[K]> extends {
    '~options': {
      primary: true;
    };
  }
    ? K
    : never;
}[keyof Properties];
type InferBuilderValue<Builder> = Builder extends {
  '~type'?: {
    value: infer Value;
  };
  '~options'?: infer Options;
}
  ? MaybeHidden<
      MaybeOpt<
        MaybeScalarRef<
          MaybeNullable<MaybeRelationRef<MaybeMapToPk<MaybeArray<Value, Options>, Options>, Options>, Options>,
          Options
        >,
        Options
      >,
      Options
    >
  : never;
type MaybeArray<Value, Options> = Options extends {
  array: true;
}
  ? Value[]
  : Value;
type MaybeMapToPk<Value, Options> = Options extends {
  mapToPk: true;
}
  ? Primary<Value>
  : Value;
type MaybeNullable<Value, Options> = Options extends {
  nullable: true;
}
  ? Value | null | undefined
  : Value;
type MaybeRelationRef<Value, Options> = Options extends {
  mapToPk: true;
}
  ? Value
  : Options extends {
        ref: true;
        kind: '1:1';
      }
    ? Value extends object
      ? Ref<Value>
      : never
    : Options extends {
          ref: true;
          kind: 'm:1';
        }
      ? Value extends object
        ? Ref<Value>
        : never
      : Options extends {
            kind: '1:m';
          }
        ? Value extends object
          ? Collection<Value>
          : never
        : Options extends {
              kind: 'm:n';
            }
          ? Value extends object
            ? Collection<Value>
            : never
          : Value;
type MaybeScalarRef<Value, Options> = Options extends {
  kind: '1:1' | 'm:1' | '1:m' | 'm:n';
}
  ? Value
  : Options extends {
        ref: true;
      }
    ? ScalarReference<Value>
    : Value;
type MaybeOpt<Value, Options> = Options extends {
  mapToPk: true;
}
  ? Value extends Opt<infer OriginalValue>
    ? OriginalValue
    : Value
  : Options extends
        | {
            autoincrement: true;
          }
        | {
            onCreate: Function;
          }
        | {
            default: string | string[] | number | number[] | boolean | null | Date | Raw;
          }
        | {
            defaultRaw: string;
          }
        | {
            persist: false;
          }
        | {
            version: true;
          }
        | {
            formula: string | ((...args: any[]) => any);
          }
    ? Opt<NonNullable<Value>> | Extract<Value, null | undefined>
    : Value;
type MaybeHidden<Value, Options> = Options extends {
  hidden: true;
}
  ? Hidden<NonNullable<Value>> | Extract<Value, null | undefined>
  : Value;
type ValueOf<T extends Dictionary> = T[keyof T];
type IsUnion<T, U = T> = T extends U ? ([U] extends [T] ? false : true) : false;
