'use strict';
import { crudResultTypes } from '../../../../fd-toolbox/types/crud/crud-result-type.js';
import { validateResource, createValidationDetailResult, validateId } from '../validations/meta-validations.js';
import { syncInfosWithResourceMeta } from './relation-syncs.js';
import { publishMessage } from '../messaging/messages.js';
import { isUuidSet, isEmptyNullOrUndefined } from '../../../../fd-toolbox/functions/value-checking-functions.js';
import { checkResourcePermission } from './helpers/cruds-permission-checker.js';
import { setInvalidCrudResult } from '../../../../fd-toolbox/types/crud/crud-results.js';
import { getResourceMeta } from '../services/metas.js';
import { checkSupportedCrudActions } from '../services/crud-actions.js';
import { runAfterCreateHandler, runAfterUpdateCrudHandler, runPreDeleteHandler, runAfterDeleteHandler, runPreCreateHandler, runPreUpdateHandler } from './helpers/crud-event-handler.js';
import { createError } from '../../../../fd-toolbox/errors/errors.js';
import { getUserId } from '../auth/users/current-user-id-provider.js';
import { getResource, createResourceDirectlyInDb, updateResource } from '../db/db.js';
import { crudActions, propertyTypes } from '../../../../fd-toolbox/enums/enums.js';
import { withOptionalUserIdProps } from '../../../../fd-toolbox/base-resource/props/with-optional-user-id-props.js';
import { withWorkspaceIdProps } from '../../../../fd-toolbox-core/server/base-resources/props/with-workspace-id-props.js';
import { logWarning } from '../../../../fd-toolbox/server/logging/logger.js';
import { httpStatusCodes } from '../../../../fd-toolbox/constants/http-status-codes.js';
import { getObjectValues } from '../../../../fd-toolbox/lib/utils.js';
import { getCrudUpdateConfigFromProp, doNotAllowToChangeWorkspaceId, validateAndDeleteResource, prepareResourceBeforeUpdate, modifyResourceFromDatabase, getResourceForCreation } from './crud.js';
import { metaValidationMessages } from '../constants/meta-validation-messages.js';
import { toolboxErrorMessages } from '../../../../fd-toolbox/constants/toolbox-error-messages-constants.js';
import { warningMessages } from '../constants/warning-messages.js';
import { metaErrorMessages } from '../../constants/meta-error-messages-constants.js';
import { isNumber } from '../../../../fd-toolbox/types/ensure-type.js';

var __defProp=Object['defineProperty'],__name=(_0xf987c7,_0xee9e61)=>__defProp(_0xf987c7,'name',{'value':_0xee9e61,'configurable':!![]});async function crudCreate(_0x292c33){return _0x292c33['isCreate']=!![],crudUpdate(_0x292c33);}__name(crudCreate,'crudCreate');async function crudUpdate(_0x5d5e54){const _0x2b7fb0=getCrudUpdateConfigFromProp(_0x5d5e54),_0x5c8dbd=_0x2b7fb0['resourceName'],_0x4ba2f2=await prepareAndValidateConfig(_0x2b7fb0,_0x5c8dbd);let _0x15a18d;!_0x2b7fb0['isCreate']&&(_0x15a18d=await getResource({'resourceName':_0x4ba2f2['resourceName'],'id':_0x2b7fb0['resource']['id']},![]));const _0x313e62={'type':crudResultTypes['success'],'validationResult':createDefaultValidationResult()},_0x18d816=await modifyResource(_0x2b7fb0,_0x313e62,_0x4ba2f2);if(!_0x18d816)return _0x313e62;const _0x1e6988=getObjectValues(withWorkspaceIdProps)['filter'](_0x392468=>!Object['hasOwn'](_0x18d816,_0x392468))['length']===-0x280*-0x2+0x6e1*-0x1+0x1e1;return _0x1e6988&&await doNotAllowToChangeWorkspaceId(_0x313e62,_0x18d816,_0x15a18d),await runPreCreateAndUpdateCrudUpdateHandlers(_0x2b7fb0,_0x4ba2f2,_0x313e62,_0x18d816,_0x15a18d),await validateAndUpdateResource(_0x2b7fb0,_0x4ba2f2,_0x313e62,_0x18d816,_0x15a18d),_0x2b7fb0['isCreate']&&await runAfterCreateHandler(_0x4ba2f2,_0x313e62,_0x18d816),throwErrorOnNonSuccess(_0x313e62,_0x2b7fb0['throwOnNonSuccess']),logWarningIfValidationResultFalse(_0x313e62,_0x5c8dbd,_0x2b7fb0),_0x313e62;}__name(crudUpdate,'crudUpdate');async function validateAndUpdateResource(_0x56f841,_0xbbf09,_0x35f106,_0x3dfa77,_0x46bb16){_0x35f106['validationResult']?.['isValid']&&(_0x35f106['validationResult']=await validateResource(_0x3dfa77,_0xbbf09)),_0x35f106['validationResult']?.['isValid']?await updateValidResource(_0x3dfa77,_0x56f841,_0x35f106,_0xbbf09,_0x46bb16):_0x35f106['type']=crudResultTypes['notValid'];}__name(validateAndUpdateResource,'validateAndUpdateResource');async function checkIsResourceExistsInDb(_0x2515d1,_0x426953){let _0x398bf7;_0x2515d1['isUpsert']&&(isUuidSet(_0x2515d1['resource']['id'])&&(_0x398bf7=await getResource({'resourceName':_0x426953['resourceName'],'id':_0x2515d1['resource']['id']},![])),_0x2515d1['isCreate']=isEmptyNullOrUndefined(_0x398bf7));}__name(checkIsResourceExistsInDb,'checkIsResourceExistsInDb');async function updateValidResource(_0x214404,_0x162cda,_0xb1db69,_0x1d1245,_0x25f649){let _0x471745=_0x214404;_0x1d1245['isPersistent']&&(normalizeModifiedResource(_0x214404,_0x1d1245),_0x471745=_0x162cda['isCreate']?await createResourceDirectlyInDb(_0x214404,_0x1d1245['resourceName']):await updateResource(_0x214404,_0x1d1245['resourceName']));await runAfterUpdateCrudHandler(_0x162cda,_0x1d1245,_0xb1db69,_0x471745,_0x25f649);const _0x3e55a7={'messageSubType':_0x1d1245['resourceName'],'crudServiceResult':_0xb1db69,'modifiedResource':_0x471745,'crudUpdateConfig':_0x162cda,'originalResource':_0x25f649};await publishMessage(_0x3e55a7),_0x162cda['propertyRelationSyncInfos']&&await syncRelationsIfNeeded(_0x1d1245,_0x471745,_0xb1db69,_0x162cda['propertyRelationSyncInfos']);}__name(updateValidResource,'updateValidResource');async function syncRelationsIfNeeded(_0x26b120,_0x34f67a,_0x507220,_0x54333f){_0x54333f['length']>-0xd*0x296+0x10*-0x1d3+0x3ece&&_0x507220['type']!==crudResultTypes['notValid']&&await syncInfosWithResourceMeta(_0x54333f,_0x26b120,_0x34f67a);}__name(syncRelationsIfNeeded,'syncRelationsIfNeeded');function logWarningIfValidationResultFalse(_0x45f007,_0x45cfd3,_0x3d906e){if(_0x45f007['type']!==crudResultTypes['success']){let _0x2ffc16='In\x20'+_0x45f007['result']+'\x20Non\x20Success\x20result.\x20Resource:\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'+_0x45cfd3+'\x20Result:\x20'+_0x45f007['type']+'.\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20UserId:\x20'+_0x3d906e['userId'];if(!_0x45f007?.['validationResult']?.['isValid']){const _0x5f5d21=JSON['stringify'](_0x45f007['validationResult'],void(0x251b*-0x1+0x2*0xead+0x1*0x7c1),0x1c55+0x1*-0x21ea+0x597);_0x2ffc16+='\x20ValidationResult:\x20'+_0x5f5d21;}logWarning(_0x2ffc16);}}__name(logWarningIfValidationResultFalse,'logWarningIfValidationResultFalse');async function crudDelete(_0x40dcc2){const _0x9a5a6e=_0x40dcc2['resourceName'];await trySetUserIdOnDeleteConfig(_0x40dcc2);const _0x129596=await getResourceMeta(_0x9a5a6e);checkSupportedCrudActions(_0x129596,crudActions['delete']);const _0x13a497=await getResource({'resourceName':_0x129596['resourceName'],'id':_0x40dcc2['resourceId']});if(!_0x13a497){const _0x3fb8e6=createValidationDetailResult(metaValidationMessages['resourceNameNotFound'],toolboxErrorMessages['resourceNotFound']['replace']('{0}',_0x9a5a6e)['replace']('{1}',_0x40dcc2['resourceId']),_0x9a5a6e,httpStatusCodes['notFound']);return setInvalidCrudResult(_0x3fb8e6);}await checkResourcePermission(_0x129596,crudActions['delete'],_0x40dcc2['userId'],_0x13a497);const _0x31464a={'type':crudResultTypes['success'],'validationResult':createDefaultValidationResult()};return await runPreDeleteHandler(_0x9a5a6e,_0x13a497,_0x31464a),await validateAndDeleteResource(_0x40dcc2,_0x31464a,_0x129596),await runAfterDeleteHandler(_0x9a5a6e,_0x13a497,_0x31464a),_0x31464a;}__name(crudDelete,'crudDelete');async function trySetUserIdOnConfig(_0x58cd04){if(_0x58cd04['userId'])return;if(withOptionalUserIdProps['userId']in _0x58cd04['resource']&&_0x58cd04['resource']['id'])_0x58cd04['userId']=_0x58cd04['resource']['userId'];!_0x58cd04['userId']&&(_0x58cd04['userId']=await getUserId(),logWarning(warningMessages['crudServiceNoUserId']['replace']('{0}',_0x58cd04['userId'])));}__name(trySetUserIdOnConfig,'trySetUserIdOnConfig');async function trySetUserIdOnDeleteConfig(_0x22d303){if(_0x22d303['userId'])return;_0x22d303['userId']=await getUserId();}__name(trySetUserIdOnDeleteConfig,'trySetUserIdOnDeleteConfig');async function runPreCreateAndUpdateCrudUpdateHandlers(_0x42b7b2,_0x3b208b,_0x2dca3c,_0x9b727b,_0x553f3d){_0x42b7b2['isCreate']?await runPreCreateHandler(_0x42b7b2,_0x3b208b,_0x2dca3c,_0x9b727b):await runPreUpdateHandler(_0x42b7b2,_0x3b208b,_0x2dca3c,_0x9b727b,_0x553f3d);}__name(runPreCreateAndUpdateCrudUpdateHandlers,'runPreCreateAndUpdateCrudUpdateHandlers');async function prepareAndValidateConfig(_0x31528a,_0x5cb4d2){await prepareResourceBeforeUpdate(_0x31528a),await trySetUserIdOnConfig(_0x31528a);const _0x330028=await getResourceMeta(_0x5cb4d2);await checkIsResourceExistsInDb(_0x31528a,_0x330028);const _0x44ddff=_0x31528a['isCreate']?crudActions['create']:crudActions['update'];return checkSupportedCrudActions(_0x330028,_0x44ddff),await checkResourcePermission(_0x330028,_0x44ddff,_0x31528a['userId'],_0x31528a['resource']),checkMirrorManyToManyResource(_0x330028,_0x31528a['resource']),_0x330028;}__name(prepareAndValidateConfig,'prepareAndValidateConfig');function checkMirrorManyToManyResource(_0x8eb041,_0x5c6fa6){if(_0x8eb041['manyToManyInfo']?.['isMirrorManyToManyResource']){const _0x5e34b6=_0x8eb041['manyToManyInfo']['manyToManyFirstPropertyName'],_0x140717=_0x8eb041['manyToManyInfo']['manyToManySecondPropertyName'],_0x3e5018=_0x5c6fa6[_0x5e34b6],_0x3289ae=_0x5c6fa6[_0x140717];if(_0x3e5018===_0x3289ae)throw createError(metaErrorMessages['mirrorManyToManyResourcesAreSame']);}}__name(checkMirrorManyToManyResource,'checkMirrorManyToManyResource');async function modifyResource(_0x1d61c1,_0xf55ec2,_0x1b6635){let _0xeb2f2d=_0x1d61c1['resource'];if(!_0x1d61c1['isCreate']){const _0x42f1b6=validateId(_0x1d61c1['resource']['id']);if(!_0x42f1b6['isValid'])return _0xf55ec2['validationResult']=_0x42f1b6,_0xf55ec2['type']=crudResultTypes['notValid'],void(-0x995+-0x2*0x4df+-0x33*-0x61);_0x1b6635['isPersistent']&&(_0xeb2f2d=await modifyResourceFromDatabase(_0xeb2f2d,_0x1b6635,_0x1d61c1['userId'],_0x1d61c1['isCalledFromOutside']));}else _0xeb2f2d=await getResourceForCreation(_0xeb2f2d,_0x1b6635,_0x1d61c1['userId'],_0x1d61c1['isCalledFromOutside']);return _0xeb2f2d;}__name(modifyResource,'modifyResource');function throwErrorOnNonSuccess(_0x2c62d5,_0x2e8844){if(_0x2e8844&&_0x2c62d5['type']!==crudResultTypes['success'])throw createError('CrudResult\x20is\x20not\x20Success.\x20Details:\x20'+JSON['stringify'](_0x2c62d5['validationResult']));}__name(throwErrorOnNonSuccess,'throwErrorOnNonSuccess');function createDefaultValidationResult(){const _0x172dab={'isValid':!![],'details':[]};return _0x172dab;}__name(createDefaultValidationResult,'createDefaultValidationResult');function normalizeModifiedResource(_0x50c745,_0x1e8c58){const _0x3ca4f1=Object['keys'](_0x50c745);for(const _0x5c3e0b of _0x3ca4f1){const _0x5e3165=_0x50c745[_0x5c3e0b],_0x47edde=_0x1e8c58['properties'][_0x5c3e0b];_0x47edde&&((_0x5e3165===void(-0x6f9+-0x21ea+0x28e3)||isInvalidOptionalNumber(_0x5e3165,_0x47edde))&&(_0x50c745[_0x5c3e0b]=null));}}__name(normalizeModifiedResource,'normalizeModifiedResource');function isInvalidOptionalNumber(_0xc4e8ff,_0x197bbf){const _0x1e9be3=_0x197bbf['type']===propertyTypes['integer']||_0x197bbf['type']===propertyTypes['number'],_0x2d75d6=isNumber(_0xc4e8ff)&&isNaN(_0xc4e8ff);return _0x2d75d6&&!_0x197bbf['required']&&_0x1e9be3;}__name(isInvalidOptionalNumber,'isInvalidOptionalNumber');

export { checkIsResourceExistsInDb, crudCreate, crudDelete, crudUpdate, logWarningIfValidationResultFalse, syncRelationsIfNeeded, trySetUserIdOnConfig, trySetUserIdOnDeleteConfig, updateValidResource, validateAndUpdateResource };
