"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.__ΩEntityPick = exports.BaseEntity = void 0;
exports.getDirtyDetails = getDirtyDetails;
exports.revertDirtyEntity = revertDirtyEntity;
exports.getDirtyFields = getDirtyFields;
exports.isEntityDirty = isEntityDirty;
exports.isFieldDirty = isFieldDirty;
exports.getFieldOriginal = getFieldOriginal;
exports.getEntityOriginal = getEntityOriginal;
exports.getKeyedEntities = getKeyedEntities;
exports.getKeyedGroupedEntities = getKeyedGroupedEntities;
exports.getEntitiesById = getEntitiesById;
exports.getEntitiesByIdWithKeyName = getEntitiesByIdWithKeyName;
exports.resolveRelated = resolveRelated;
exports.resolveRelatedByPivot = resolveRelatedByPivot;
exports.resolveRelatedByPivotForOne = resolveRelatedByPivotForOne;
const __ΩRecord = ['K', 'T', 'Record', 'l\'e#"Rb!b"Pde"!N#!w#y'];
const __ΩOmit = ['T', 'K', () => __ΩPick, () => __ΩExclude, 'Omit', 'b!b"e!!e!!ge!"o$#o##w%y'];
const __ΩPick = ['T', 'K', 'Pick', 'l+e#!e"!fRb!b"Pde""N#!w#y'];
const __ΩInstanceType = ['T', 'args', 'new', 'InstanceType', 'l>e"!R"RPde#!P"@2"h"!/#qk#\'QRb!Pde"!p)w$y'];
const __ΩExclude = ['T', 'U', 'Exclude', 'l6!Re$!RPe#!e$"qk#%QRb!b"Pde"!p)w#y'];
function __assignType(fn, args) {
    fn.__type = args;
    return fn;
}
const core_1 = require("@deepkit/core");
/*@ts-ignore*/
var { __ΩFilterQuery, __ΩActiveRecordClassType } = require('@deepkit/orm');
const orm_1 = require("@deepkit/orm");
const type_1 = require("@deepkit/type");
const lodash_1 = require("lodash");
/*@ts-ignore*/
var { __ΩEntityFields, __ΩEntityClassFields } = require('./common');
const common_1 = require("./common");
function getDirtyDetails(entity) {
    const classState = (0, orm_1.getClassState)(type_1.ReflectionClass.from((0, core_1.getClassTypeFromInstance)(entity)));
    const instanceState = (0, orm_1.getInstanceState)(classState, entity);
    const lastSnapshot = instanceState.getSnapshot();
    const currentSnapshot = classState.snapshot(entity);
    const changeSet = classState.changeDetector(lastSnapshot, currentSnapshot, entity);
    const changedFields = Object.keys(changeSet?.$set || {});
    return Object.fromEntries(changedFields.map(__assignType(f => [
        f,
        {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            original: lastSnapshot[f],
            current: currentSnapshot[f]
        }
    ], ['f', '', 'P"2!"/"'])));
}
getDirtyDetails.__type = ['entity', () => __ΩRecord, 'original', 'current', 'getDirtyDetails', 'P"2!"P""f4#""f4$Mo"#/%'];
function revertDirtyEntity(entity) {
    const original = getEntityOriginal(entity);
    for (const [field, value] of Object.entries(original)) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        entity[field] = value;
    }
}
revertDirtyEntity.__type = [() => orm_1.ActiveRecord, 'entity', 'revertDirtyEntity', 'PP7!2""/#'];
function getDirtyFields(entity) {
    return Object.keys(getDirtyDetails(entity));
}
getDirtyFields.__type = ['entity', 'getDirtyFields', 'P"2!"gF/"'];
function isEntityDirty(entity) {
    return getDirtyFields(entity).length > 0;
}
isEntityDirty.__type = [() => orm_1.ActiveRecord, 'entity', 'isEntityDirty', 'PP7!2""/#'];
function isFieldDirty(entity, field) {
    return getDirtyFields(entity).includes(field);
}
isFieldDirty.__type = ['entity', 'field', 'isFieldDirty', 'P"2!"g2""/#'];
function getFieldOriginal(entity, field) {
    const dirtyDetails = getDirtyDetails(entity);
    const fieldDetails = dirtyDetails[field];
    return fieldDetails?.original;
}
getFieldOriginal.__type = ['entity', 'field', 'getFieldOriginal', 'P"2!"2"P""f-J/#'];
function getEntityOriginal(entity) {
    return (0, orm_1.getInstanceStateFromItem)(entity).getSnapshot();
}
getEntityOriginal.__type = ['entity', () => __ΩEntityFields, 'getEntityOriginal', 'P"2!"o""/#'];
class BaseEntity extends orm_1.ActiveRecord {
}
exports.BaseEntity = BaseEntity;
BaseEntity.__type = [() => orm_1.ActiveRecord, 'BaseEntity', 'P7!5w"'];
const __ΩEntityPick = ['T', 'K', () => orm_1.ActiveRecord, () => __ΩPick, 'EntityPick', 'b!b"PP7#e"!e""o$#Kw%y'];
exports.__ΩEntityPick = __ΩEntityPick;
const __ΩIGetEntityOptions = ['Schema', 'Field', 'schema', 'ids', 'keyField', 'fields', () => __ΩFilterQuery, () => __ΩInstanceType, 'filter', () => orm_1.DatabaseAdapter, () => orm_1.DatabaseSession, 'txn', 'IGetEntityOptions', 'b!b"Pe"!4#"F4$e""4%8e""F4&8e"!o("o\'"4)8PP7*7+4,8Mw-y'];
async function getKeyedEntities(options) {
    const { keyField, entities } = await getEntitiesByIdWithKeyName(options);
    return (0, lodash_1.keyBy)(entities, keyField);
}
getKeyedEntities.__type = [() => __ΩIGetEntityOptions, 'options', 'getKeyedEntities', 'P""o!#2""/#'];
async function getKeyedGroupedEntities(options) {
    const { keyField, entities } = await getEntitiesByIdWithKeyName(options);
    return (0, lodash_1.groupBy)(entities, keyField);
}
getKeyedGroupedEntities.__type = [() => __ΩIGetEntityOptions, 'options', 'getKeyedGroupedEntities', 'P""o!#2""/#'];
async function getEntitiesById(options) {
    const { entities } = await getEntitiesByIdWithKeyName(options);
    return entities;
}
getEntitiesById.__type = [() => __ΩIGetEntityOptions, 'options', 'getEntitiesById', 'P""o!#2""/#'];
async function getEntitiesByIdWithKeyName({ schema, ids, keyField, fields, filter, txn }) {
    const __ΩReturnType = [() => fields, () => __ΩInstanceType, () => __ΩActiveRecordClassType, () => __ΩEntityPick, () => __ΩInstanceType, () => __ΩActiveRecordClassType, () => __ΩEntityClassFields, () => __ΩActiveRecordClassType, 'ReturnType', 'l8n#o""Rn&o%"n(o\'"go$#RPi!-qk#)Qw)y'];
    const db = schema.getDatabase();
    const resolvedKeyField = keyField ?? (0, common_1.getPKFieldForEntity)(schema);
    ids = (0, lodash_1.uniq)((0, lodash_1.compact)(ids));
    if (!ids.length) {
        return {
            keyField: resolvedKeyField,
            entities: []
        };
    }
    const query = txn ? txn.query(schema) : db.query(schema);
    const entities = fields
        ? await query
            .filter({ [resolvedKeyField]: { $in: ids }, ...filter })
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            .select(...fields)
            .find()
        : await query.filter({ [resolvedKeyField]: { $in: ids }, ...filter }).find();
    return {
        keyField: resolvedKeyField,
        entities: entities
    };
}
getEntitiesByIdWithKeyName.__type = [() => __ΩIGetEntityOptions, 'param0', 'getEntitiesByIdWithKeyName', 'P""o!#2""/#'];
const __ΩIResolveRelatedOptions = ['Schema', 'IdKey', 'RelatedSchema', 'RelatedKey', 'RelatedFields', 'src', 'srcIdField', 'targetField', 'targetSchema', 'targetFields', () => orm_1.DatabaseAdapter, () => orm_1.DatabaseSession, 'txn', 'IResolveRelatedOptions', 'b!b"b#b$b%Pe"!F4&e""4\'e"$4(e"#4)e"%F4*8PP7+7,4-8Mw.y'];
async function resolveRelated(options) {
    const { src, srcIdField, targetField, targetSchema, targetFields } = options;
    const __ΩRelatedType = [() => targetFields, () => __ΩInstanceType, () => options, () => __ΩIResolveRelatedOptions, () => __ΩEntityPick, () => __ΩInstanceType, () => options, () => __ΩIResolveRelatedOptions, () => options, () => __ΩIResolveRelatedOptions, 'RelatedType', 'ljPdi#""h!!""o$&qe!!!jo""RPdi\'""h!!""o(&qe!!!jo&"Pdi)""""h!!o*&qe!!!jo%#RPi!-qk#;Qw+y'];
    const __ΩRelatedFieldType = [() => options, () => __ΩIResolveRelatedOptions, () => options, () => __ΩIResolveRelatedOptions, () => options, () => __ΩIResolveRelatedOptions, () => __ΩRelatedType, () => options, () => __ΩIResolveRelatedOptions, () => __ΩRelatedType, 'RelatedFieldType', 'l]n\'RPdPdi%"""h!!"o&&qe!!!jN#"Rn*RPdPdi("""h!!"o)&qe!!!jN@!RP,Pdi!h!!""""o"&qe!!!jPdi#"h!!"""o$&qe!!!jfqk&CQw+y'];
    const __ΩReturnType = [() => __ΩOmit, () => options, () => __ΩIResolveRelatedOptions, () => options, () => __ΩIResolveRelatedOptions, () => __ΩRelatedFieldType, 'ReturnType', 'PPdi"h!!""""o#&qe!!!jPdi$"h!!"""o%&qe!!!jo!#n&Kw\'y'];
    if (!src.length) {
        return [];
    }
    const subentitiesById = await getKeyedEntities({
        ids: src.map(__assignType(e => e[srcIdField], ['e', '', 'P"2!"/"'])),
        schema: targetSchema,
        fields: targetFields,
        txn: options.txn
    });
    src.forEach(__assignType(e => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        e[targetField] = subentitiesById[e[srcIdField]];
    }, ['e', '', 'P"2!"/"']));
    return src;
}
resolveRelated.__type = [() => __ΩIResolveRelatedOptions, 'options', 'resolveRelated', 'P"""""o!&2""/#'];
const __ΩIResolveRelatedByPivotOptions = ['Schema', 'SrcIdField', 'PivotSchema', 'PivotIdKey', 'PivotRelatedKey', 'RelatedSchema', 'RelatedKey', 'RelatedFields', 'src', 'srcIdField', 'pivotSchema', 'pivotIdKey', 'pivotRelatedKey', () => __ΩFilterQuery, () => __ΩInstanceType, 'pivotFilter', 'targetField', 'targetSchema', 'targetFields', () => orm_1.DatabaseAdapter, () => orm_1.DatabaseSession, 'txn', 'IResolveRelatedByPivotOptions', 'b!b"b#b$b%b&b\'b(Pe"!F4)e""4*8e"#4+e"$4,e"%4-e"#o/"o."408e"\'41e"&42e"(F438PP7475468Mw7y'];
async function resolveRelatedByPivot(options) {
    const { src, srcIdField, pivotSchema, pivotIdKey, pivotRelatedKey, pivotFilter, targetField, targetSchema, targetFields } = options;
    const __ΩRelatedType = [() => targetFields, () => __ΩInstanceType, () => options, () => __ΩIResolveRelatedByPivotOptions, () => __ΩEntityPick, () => __ΩInstanceType, () => options, () => __ΩIResolveRelatedByPivotOptions, () => options, () => __ΩIResolveRelatedByPivotOptions, 'RelatedType', 'lsPdi#"""""h!!""o$)qe!!!jo""RPdi\'"""""h!!""o()qe!!!jo&"Pdi)"""""""h!!o*)qe!!!jo%#RPi!-qk#>Qw+y'];
    const __ΩRelatedTypeWithPivot = [() => __ΩRelatedType, () => __ΩInstanceType, () => options, () => __ΩIResolveRelatedByPivotOptions, 'pivot', 'RelatedTypeWithPivot', 'Pn!PPdi#""h!!"""""o$)qe!!!jo""4%MKw&y'];
    const __ΩRelatedFieldType = [() => options, () => __ΩIResolveRelatedByPivotOptions, () => __ΩRelatedTypeWithPivot, 'RelatedFieldType', 'l\'n#FRPdPdi!""""""h!!"o")qe!!!jN#!w$y'];
    const __ΩReturnType = [() => options, () => __ΩIResolveRelatedByPivotOptions, () => __ΩRelatedFieldType, 'ReturnType', 'PPdi!h!!"""""""o")qe!!!jn#Kw$y'];
    if (!src.length) {
        return [];
    }
    const sourcePkField = srcIdField ?? (0, common_1.getPKFieldForEntityInstance)(src[0]);
    const pivotEntitiesBySourceId = await getKeyedGroupedEntities({
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        ids: src.map(__assignType(e => e[sourcePkField], ['e', '', 'P"2!"/"'])),
        schema: pivotSchema,
        keyField: pivotIdKey,
        filter: pivotFilter,
        txn: options.txn
    });
    const relatedEntitiesById = await getKeyedEntities({
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        ids: Object.values(pivotEntitiesBySourceId).flatMap(__assignType(p => p.map(__assignType(p => p[pivotRelatedKey], ['p', '', 'P"2!"/"'])), ['p', '', 'P"2!"/"'])),
        schema: targetSchema,
        fields: targetFields,
        txn: options.txn
    });
    src.forEach(__assignType(e => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        e[targetField] =
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            pivotEntitiesBySourceId[e[sourcePkField]]?.map(__assignType(p => ({
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                ...relatedEntitiesById[p[pivotRelatedKey]],
                pivot: p
            }), ['p', '', 'P"2!"/"'])) ?? [];
    }, ['e', '', 'P"2!"/"']));
    return src;
}
resolveRelatedByPivot.__type = [() => __ΩIResolveRelatedByPivotOptions, 'options', 'resolveRelatedByPivot', 'P""""""""o!)2""/#'];
async function resolveRelatedByPivotForOne(options) {
    return (await resolveRelatedByPivot({
        ...options,
        src: [options.src]
    }))[0];
}
resolveRelatedByPivotForOne.__type = [() => __ΩOmit, () => __ΩIResolveRelatedByPivotOptions, "src", 'src', 'options', 'resolveRelatedByPivotForOne', 'PP""""""""o").#o!#P"4$MK2%"/&'];
//# sourceMappingURL=entity.js.map