import { CompositeKey, EntityPermissionType, EntitySaveOptions, LogError, Metadata } from '@memberjunction/core';
export class EntityCRUDHandler {
    static async createEntity(entityName, data, user) {
        try {
            const md = new Metadata();
            const entity = await md.GetEntityObject(entityName, user);
            if (!entity.CheckPermissions(EntityPermissionType.Create, false)) {
                return {
                    success: false,
                    error: `User ${user.Name} does not have permission to create ${entityName} records`
                };
            }
            entity.NewRecord();
            const options = new EntitySaveOptions();
            if (data.options) {
                const { IgnoreDirtyState, SkipEntityAIActions, SkipEntityActions, ReplayOnly, SkipOldValuesCheck } = data.options;
                if (IgnoreDirtyState !== undefined)
                    options.IgnoreDirtyState = !!IgnoreDirtyState;
                if (SkipEntityAIActions !== undefined)
                    options.SkipEntityAIActions = !!SkipEntityAIActions;
                if (SkipEntityActions !== undefined)
                    options.SkipEntityActions = !!SkipEntityActions;
                if (ReplayOnly !== undefined)
                    options.ReplayOnly = !!ReplayOnly;
                if (SkipOldValuesCheck !== undefined)
                    options.SkipOldValuesCheck = !!SkipOldValuesCheck;
                delete data.options;
            }
            for (const key in data) {
                entity.Set(key, data[key]);
            }
            const validationResult = entity.Validate();
            if (!validationResult.Success) {
                return {
                    success: false,
                    error: 'Validation failed',
                    validationErrors: validationResult.Errors
                };
            }
            const saveSuccess = await entity.Save(options);
            if (!saveSuccess) {
                const latestResult = entity.LatestResult;
                return {
                    success: false,
                    error: latestResult?.Message || 'Failed to create entity',
                    details: latestResult
                };
            }
            const entityData = await entity.GetDataObject();
            return { success: true, entity: entityData };
        }
        catch (error) {
            LogError(error);
            return { success: false, error: error?.message || 'Unknown error' };
        }
    }
    static async getEntity(entityName, id, relatedEntities = null, user) {
        try {
            const md = new Metadata();
            const entity = await md.GetEntityObject(entityName, user);
            if (!entity.CheckPermissions(EntityPermissionType.Read, false)) {
                return {
                    success: false,
                    error: `User ${user.Name} does not have permission to read ${entityName} records`
                };
            }
            const compositeKey = this.createCompositeKeyFromId(entity, id);
            const loadSuccess = await entity.InnerLoad(compositeKey, relatedEntities);
            if (!loadSuccess) {
                return {
                    success: false,
                    error: `${entityName} with ID ${id} not found`
                };
            }
            const entityData = await entity.GetDataObject();
            return { success: true, entity: entityData };
        }
        catch (error) {
            LogError(error);
            return { success: false, error: error?.message || 'Unknown error' };
        }
    }
    static async updateEntity(entityName, id, data, user) {
        try {
            const md = new Metadata();
            const entity = await md.GetEntityObject(entityName, user);
            if (!entity.CheckPermissions(EntityPermissionType.Update, false)) {
                return {
                    success: false,
                    error: `User ${user.Name} does not have permission to update ${entityName} records`
                };
            }
            const compositeKey = this.createCompositeKeyFromId(entity, id);
            const loadSuccess = await entity.InnerLoad(compositeKey);
            if (!loadSuccess) {
                return {
                    success: false,
                    error: `${entityName} with ID ${id} not found`
                };
            }
            const options = new EntitySaveOptions();
            if (data.options) {
                const { IgnoreDirtyState, SkipEntityAIActions, SkipEntityActions, ReplayOnly, SkipOldValuesCheck } = data.options;
                if (IgnoreDirtyState !== undefined)
                    options.IgnoreDirtyState = !!IgnoreDirtyState;
                if (SkipEntityAIActions !== undefined)
                    options.SkipEntityAIActions = !!SkipEntityAIActions;
                if (SkipEntityActions !== undefined)
                    options.SkipEntityActions = !!SkipEntityActions;
                if (ReplayOnly !== undefined)
                    options.ReplayOnly = !!ReplayOnly;
                if (SkipOldValuesCheck !== undefined)
                    options.SkipOldValuesCheck = !!SkipOldValuesCheck;
                delete data.options;
            }
            for (const key in data) {
                entity.Set(key, data[key]);
            }
            if (!entity.Dirty && !options.IgnoreDirtyState) {
                const entityData = await entity.GetDataObject();
                return { success: true, entity: entityData };
            }
            const validationResult = entity.Validate();
            if (!validationResult.Success) {
                return {
                    success: false,
                    error: 'Validation failed',
                    validationErrors: validationResult.Errors
                };
            }
            const saveSuccess = await entity.Save(options);
            if (!saveSuccess) {
                const latestResult = entity.LatestResult;
                return {
                    success: false,
                    error: latestResult?.Message || 'Failed to update entity',
                    details: latestResult
                };
            }
            const entityData = await entity.GetDataObject();
            return { success: true, entity: entityData };
        }
        catch (error) {
            LogError(error);
            return { success: false, error: error?.message || 'Unknown error' };
        }
    }
    static async deleteEntity(entityName, id, options, user) {
        try {
            const md = new Metadata();
            const entity = await md.GetEntityObject(entityName, user);
            if (!entity.CheckPermissions(EntityPermissionType.Delete, false)) {
                return {
                    success: false,
                    error: `User ${user.Name} does not have permission to delete ${entityName} records`
                };
            }
            const compositeKey = this.createCompositeKeyFromId(entity, id);
            const loadSuccess = await entity.InnerLoad(compositeKey);
            if (!loadSuccess) {
                return {
                    success: false,
                    error: `${entityName} with ID ${id} not found`
                };
            }
            const deleteSuccess = await entity.Delete(options);
            if (!deleteSuccess) {
                const latestResult = entity.LatestResult;
                return {
                    success: false,
                    error: latestResult?.Message || 'Failed to delete entity',
                    details: latestResult
                };
            }
            return { success: true };
        }
        catch (error) {
            LogError(error);
            return { success: false, error: error?.message || 'Unknown error' };
        }
    }
    static createCompositeKeyFromId(entity, id) {
        if (entity.EntityInfo.PrimaryKeys.length === 1) {
            const primaryKeyField = entity.EntityInfo.PrimaryKeys[0].Name;
            const compositeKey = new CompositeKey();
            const strId = id.toString();
            compositeKey.KeyValuePairs = [
                { FieldName: primaryKeyField, Value: strId }
            ];
            return compositeKey;
        }
        else {
            throw new Error('Composite primary keys are not supported in this simplified implementation');
        }
    }
}
//# sourceMappingURL=EntityCRUDHandler.js.map