import { helper } from '../entity/wrap.js';
import { Utils } from '../utils/Utils.js';
import { inspect } from '../logging/inspect.js';
/** Represents a pending change (create, update, or delete) for a single entity. */
export class ChangeSet {
  entity;
  type;
  payload;
  meta;
  primaryKey;
  serializedPrimaryKey;
  constructor(entity, type, payload, meta) {
    this.entity = entity;
    this.type = type;
    this.payload = payload;
    this.meta = meta;
    this.meta = meta;
    this.rootMeta = meta.root;
    this.schema = helper(entity).__schema ?? meta.root.schema;
  }
  /** Returns the primary key of the entity, optionally as an object for composite keys. */
  getPrimaryKey(object = false) {
    if (!this.originalEntity) {
      this.primaryKey ??= helper(this.entity).getPrimaryKey(true);
    } else if (this.meta.compositePK) {
      this.primaryKey = this.meta.primaryKeys.map(pk => this.originalEntity[pk]);
    } else {
      this.primaryKey = this.originalEntity[this.meta.primaryKeys[0]];
    }
    if (
      !this.meta.compositePK &&
      this.meta.getPrimaryProp().targetMeta?.compositePK &&
      typeof this.primaryKey === 'object' &&
      this.primaryKey !== null
    ) {
      this.primaryKey = this.meta.getPrimaryProp().targetMeta.primaryKeys.map(childPK => {
        return this.primaryKey[childPK];
      });
    }
    if (object && this.primaryKey != null) {
      return Utils.primaryKeyToObject(this.meta, this.primaryKey);
    }
    return this.primaryKey ?? null;
  }
  /** Returns the serialized (string) form of the primary key. */
  getSerializedPrimaryKey() {
    this.serializedPrimaryKey ??= helper(this.entity).getSerializedPrimaryKey();
    return this.serializedPrimaryKey;
  }
  /** @ignore */
  [Symbol.for('nodejs.util.inspect.custom')](depth = 2) {
    const object = { ...this };
    const hidden = ['meta', 'serializedPrimaryKey'];
    hidden.forEach(k => delete object[k]);
    const ret = inspect(object, { depth });
    const name = `${this.constructor.name}<${this.meta.className}>`;
    /* v8 ignore next */
    return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
  }
}
/** Enumeration of change set operation types. */
export var ChangeSetType;
(function (ChangeSetType) {
  ChangeSetType['CREATE'] = 'create';
  ChangeSetType['UPDATE'] = 'update';
  ChangeSetType['DELETE'] = 'delete';
  ChangeSetType['UPDATE_EARLY'] = 'update_early';
  ChangeSetType['DELETE_EARLY'] = 'delete_early';
})(ChangeSetType || (ChangeSetType = {}));
