'use strict';
import { queryIndexes } from '../../../../db/types/db-types.js';
import { getTableName, Subquery, or, inArray, and, eq, count, notExists, exists, not, sql } from 'drizzle-orm';
import { getTableByResourceName, getForeignColumn } from '../../web/drizzle.js';
import { applyFilterToQuery, getTableColumn, runQuery, getTableByName } from '../../../../db/drizzle-queries.js';
import { oDataLambdaMethods, lambdaConfigNameConstants } from '../../../../../fd-toolbox/odata/odata-lambda-method.js';
import { createDynamicSelect, dbWhere, dbLeftJoin, dbGroupBy, dbHaving } from '../../../../db/db-connection.js';
import { oDataSeparators } from '../../../../../fd-toolbox/odata/odata-filter-constants.js';
import { jsBasicTypes } from '../../../../../base-repo/constants/basic-types.js';
import { oDataFilterTypes, oDataComparisonTypes, oDataLogicalOperationTypes } from '../../../../../fd-toolbox/odata/odata-enums.js';
import { columnDataTypes } from '../../db/colums-data-types.js';
import { error } from 'console';
import { createError } from '../../../../../fd-toolbox/errors/errors.js';
import { toolboxErrorMessages } from '../../../../../fd-toolbox/constants/toolbox-error-messages-constants.js';
import { convertFromPascalToCamelCase } from '../../../../../fd-toolbox/strings/casing-converter.js';
import { objectNameConstants } from '../../../../../fd-toolbox/constants/api-constants.js';
import { getBaseAndRelatedFilters } from './odata.js';
import { parseRightSideToArray } from './odata-parsers.js';
import { isString } from '../../../../../fd-toolbox/types/ensure-type.js';
import { getTable } from '../../db/db.js';
import { isNullOrUndefinedWithLogging, convertPropertyNameToTableName, getComparisonTypeFromOperation } from './odata-filters-helpers.js';
import { oDataQueryParams } from '../../../../../fd-toolbox/constants/odata-query-params.js';
import { metas } from '../../meta-core/constants/metas.js';
import { parseUtcStringToDate } from '../../../../../fd-toolbox/dates/date-time.js';
import { fileExtensionsWithoutDot } from '../../../../../base-repo/app-constants/internal-system-constants.js';
import { booleanStringValues } from '../../../../../base-repo/constants/type-string-values.js';
import { first } from '../../../../../fd-toolbox/server/collections/single-funcs.js';

var __defProp=Object['defineProperty'],__name=(_0x1cf562,_0x42b3e5)=>__defProp(_0x1cf562,'name',{'value':_0x42b3e5,'configurable':!![]});function getFilterValue(_0x26bce8,_0x44a260){return _0x26bce8['filters']?.['find'](_0x340bfd=>_0x340bfd['leftSide']===_0x44a260)?.['rightSide'];}__name(getFilterValue,'getFilterValue');async function tryFilter(_0x402869,_0x444edb,_0x2dfb3b,_0xbce6f7){const _0x8665fa=getTableName(_0x2dfb3b);let _0x15cc43=!![];if(_0x2dfb3b instanceof Subquery)error('Cannot\x20filter\x20subquery\x20directly'),_0x15cc43=![];else !_0x8665fa&&error(toolboxErrorMessages['symbolNotFound']['replace']('{0}',''+queryIndexes['tableName']));if(_0x15cc43&&_0x8665fa){const {defaultFilters:_0x4f653d,relatedFilters:_0x1a9e75}=getBaseAndRelatedFilters(_0x444edb);await addRelatedFilterToQuery(_0x402869,_0x1a9e75,_0x2dfb3b,_0xbce6f7);const _0x1870d5=_0x4f653d??[],_0x2290a3=groupBaseODataFilterByLogicalOrs(_0x1870d5),_0x580c8c=await getOrExpressions(_0x2290a3,_0x2dfb3b,_0x8665fa);_0x580c8c['length']>-0x484*-0x2+-0x1234+0x496*0x2&&applyFilterToQuery(_0x402869,or(..._0x580c8c));}return {'query':_0x402869};}__name(tryFilter,'tryFilter');async function addRelatedFilterToQuery(_0x5f1201,_0x14a1a4,_0x5adf1d,_0x2ca0fc){for(const _0x444d35 of _0x14a1a4){if(_0x444d35['leftSide']&&_0x444d35['rightSide']){const [_0x3aff82,_0x32bbeb]=_0x444d35['leftSide']['split'](oDataSeparators['propertySeparator']),_0x398cd2=await getTableByResourceName(_0x3aff82),_0x1bc70e=getTableColumn(_0x398cd2,convertFromPascalToCamelCase(_0x2ca0fc)+metas['idSuffix']),_0x1f368e=getTableColumn(_0x398cd2,_0x32bbeb),_0x45cb46=isString(_0x444d35['rightSide'])?_0x444d35['rightSide']:'',_0x3cdf27=createDynamicSelect(_0x398cd2,{'value':_0x1bc70e});dbWhere(_0x3cdf27,inArray(_0x1f368e,_0x45cb46['split'](oDataSeparators['selectSeparator'])));const _0xe8e7f8=addExpressionByType(_0x5adf1d['id'],_0x3cdf27,_0x444d35['comparisonType']);dbWhere(_0x5f1201,_0xe8e7f8);}}}__name(addRelatedFilterToQuery,'addRelatedFilterToQuery');async function getOrExpressions(_0x2de6df,_0x1b0933,_0x37f0ff){const _0x37bdd9=[];for(const _0x17e8cc of Object['values'](_0x2de6df)){const _0x3f8c4d=await getAndExpressions(_0x17e8cc,_0x1b0933,_0x37f0ff);_0x3f8c4d['length']>0x1b06+0x3fd*0x4+-0x1*0x2afa&&_0x37bdd9['push'](and(..._0x3f8c4d));}return _0x37bdd9;}__name(getOrExpressions,'getOrExpressions');async function getAndExpressions(_0x23f71e,_0x231bf6,_0x429b62){const _0x157c74=[];for(const _0x2dd476 of _0x23f71e){const _0x5a2daa=await getFilterExpression(_0x2dd476,_0x231bf6,_0x429b62);_0x5a2daa&&_0x157c74['push'](_0x5a2daa);}return _0x157c74;}__name(getAndExpressions,'getAndExpressions');async function getFilterExpression(_0x50f544,_0x118515,_0x183e2d){let _0x571679;if(_0x50f544['type']===oDataFilterTypes['lambda']){const _0x1a733e=getPredicate(_0x183e2d,_0x50f544);!isNullOrUndefinedWithLogging(objectNameConstants['predicate'],_0x1a733e)&&(_0x571679=_0x1a733e);}else {if(_0x50f544['leftSide']&&_0x50f544['leftSide']in _0x118515)_0x571679=tryGetAndExpression(_0x50f544,getTableColumn(_0x118515,_0x50f544['leftSide']));else {if(_0x50f544['leftSide']?.['endsWith'](oDataSeparators['propertySeparator']+oDataQueryParams['count'])){const _0x84089e=first(_0x50f544['leftSide']['split'](oDataSeparators['propertySeparator'])),_0x9d9d8b=_0x84089e['slice'](0x3*-0x99f+-0xd07+-0x2*-0x14f2,_0x84089e['indexOf'](metas['listSuffix'])),_0x332a97=await getTable(_0x9d9d8b),_0x4abd99=getForeignColumn(_0x332a97,_0x183e2d),_0x542462=createDynamicSelect(_0x118515,{'id':_0x118515[metas['idConstant']]});dbLeftJoin(_0x542462,_0x332a97,eq(_0x4abd99,_0x118515[metas['idConstant']])),dbGroupBy(_0x542462,_0x118515[metas['idConstant']]);const _0x436d5f=addExpressionByType(count(_0x4abd99),_0x50f544['rightSide'],_0x50f544['comparisonType']);dbHaving(_0x542462,_0x436d5f);const _0x1290f1=await runQuery(_0x542462);_0x50f544['leftSide']=metas['idConstant'],_0x50f544['comparisonType']=oDataComparisonTypes['in'],_0x50f544['rightSide']=_0x1290f1['map'](_0x173a97=>_0x173a97[metas['idConstant']]),_0x571679=tryGetAndExpression(_0x50f544,getTableColumn(_0x118515,_0x50f544['leftSide']));}}}return _0x571679;}__name(getFilterExpression,'getFilterExpression');function getPredicate(_0x3b6204,_0x44dafb){const _0x2cf47b=getTablesAndColumns(_0x3b6204,_0x44dafb);if(!_0x2cf47b)return void(0x3d6*0x3+0xf13+-0x1a95);const _0x1ef850=_0x44dafb['lambdaConfig']?.['method']===oDataLambdaMethods['all']?notExists:exists;if(_0x2cf47b['leftSide']['length']===0xc11*-0x1+0x223e+-0xac*0x21){const _0x1d4488=_0x44dafb['lambdaConfig']?.['method']===oDataLambdaMethods['all']?not(tryGetAndExpression(_0x44dafb,_0x2cf47b['leftSide1Column'])):tryGetAndExpression(_0x44dafb,_0x2cf47b['leftSide1Column']),_0x5f0963=createDynamicSelect(_0x2cf47b['enumerablePropertyTable'],{'leftSide1Column':_0x2cf47b['leftSide1Column']});return applyFilterToQuery(_0x5f0963,and(_0x2cf47b['subQueryIdEqOperator'],_0x1d4488)),_0x1ef850(_0x5f0963);}else {const _0x1192fa=_0x2cf47b['enumerablePropertyTableName']+metas['idConstant'],_0x3bbb65=eq(_0x2cf47b['enumerablePropertyTable']['id'],getTableColumn(_0x2cf47b['subPropertyTable'],_0x1192fa)),_0x54ee40=_0x44dafb['lambdaConfig']?.['method']===oDataLambdaMethods['all']?not(tryGetAndExpression(_0x44dafb,_0x2cf47b['leftSide2Column'])):tryGetAndExpression(_0x44dafb,_0x2cf47b['leftSide2Column']),_0x1932fc=createDynamicSelect(_0x2cf47b['subPropertyTable'],{'leftSide2Column':_0x2cf47b['leftSide2Column']}),_0x1304c4=and(_0x3bbb65,_0x54ee40);_0x1304c4&&dbWhere(_0x1932fc,_0x1304c4);const _0x224c15=createDynamicSelect(_0x2cf47b['enumerablePropertyTable']),_0x52b904=and(_0x2cf47b['subQueryIdEqOperator'],exists(_0x1932fc));return _0x52b904&&dbWhere(_0x224c15,_0x52b904),_0x1ef850(_0x224c15);}}__name(getPredicate,'getPredicate');function getTablesAndColumns(_0x3148f8,_0x28f666){const _0x108673=convertPropertyNameToTableName(_0x28f666['lambdaConfig']?.['baseEnumerablePropertyName']??'');if(isNullOrUndefinedWithLogging(lambdaConfigNameConstants['baseEnumerablePropertyName'],_0x108673)||isNullOrUndefinedWithLogging(lambdaConfigNameConstants['method'],_0x28f666['lambdaConfig']?.['method']))return void(0x1*-0x1405+0x26*-0x34+-0x107*-0x1b);const _0x14175b=_0x28f666['leftSide']['split'](oDataSeparators['propertySeparator']),_0x2760ea=getTableByName(_0x3148f8),_0x27019a=getTableByName(_0x108673),_0x52b9d1=getTableByName(convertPropertyNameToTableName(first(_0x14175b))),_0x3a2bd8=getTableColumn(_0x27019a,convertFromPascalToCamelCase(first(_0x14175b))),_0x218e13=getTableColumn(_0x52b9d1,convertFromPascalToCamelCase(_0x14175b[_0x14175b['length']-(0x935+0x122a+-0xdaf*0x2)])),_0x31eafb=eq(_0x2760ea['id'],getTableColumn(_0x27019a,_0x3148f8+metas['idConstant']));return {'enumerablePropertyTableName':_0x108673,'enumerablePropertyTable':_0x27019a,'subPropertyTable':_0x52b9d1,'leftSide':_0x14175b,'leftSide1Column':_0x3a2bd8,'leftSide2Column':_0x218e13,'subQueryIdEqOperator':_0x31eafb};}__name(getTablesAndColumns,'getTablesAndColumns');function groupBaseODataFilterByLogicalOrs(_0xf22e4a){const _0x3fa0ee={};let _0x2d1923=[],_0x2b7e7a=0x18aa+0x6*0x146+-0x5*0x676;_0x3fa0ee[_0x2b7e7a]=_0x2d1923;for(const _0xc99022 of _0xf22e4a){_0xc99022['logicalOperationType']===oDataLogicalOperationTypes['or']?(_0x3fa0ee[_0x2b7e7a]=_0x2d1923,_0x2d1923=[_0xc99022],_0x3fa0ee[++_0x2b7e7a]=_0x2d1923):_0x2d1923['push'](_0xc99022);}return _0x3fa0ee;}__name(groupBaseODataFilterByLogicalOrs,'groupBaseODataFilterByLogicalOrs');function tryGetAndExpression(_0x1ca4f7,_0x4f9eb1){const _0x38e0ed=tryGetConstantExpression(_0x4f9eb1['dataType'],String(_0x1ca4f7['rightSide']),_0x1ca4f7['comparisonType']);return addExpressionByType(_0x4f9eb1,_0x38e0ed,_0x1ca4f7['comparisonType']);}__name(tryGetAndExpression,'tryGetAndExpression');function tryGetConstantExpression(_0x36d6c0,_0x440f9d,_0x5b42fd){let _0x441882;if(_0x440f9d===jsBasicTypes['null'])_0x441882=[_0x440f9d];else _0x5b42fd===oDataComparisonTypes['in']||_0x5b42fd===oDataComparisonTypes['nin']?_0x441882=parseRightSideToArray(_0x440f9d):_0x441882=tryParseToType(_0x36d6c0,_0x440f9d);return _0x441882;}__name(tryGetConstantExpression,'tryGetConstantExpression');function tryParseToType(_0x3b8c9e,_0x33486c){let _0x3ad278;switch(_0x3b8c9e){case jsBasicTypes['string']:_0x3ad278=_0x33486c;break;case jsBasicTypes['bigint']:case jsBasicTypes['number']:_0x3ad278=parseFloat(_0x33486c);break;case jsBasicTypes['boolean']:_0x3ad278=_0x33486c===booleanStringValues['true'];break;case columnDataTypes['date']:_0x3ad278=parseUtcStringToDate(_0x33486c);break;case jsBasicTypes['array']:throw createError(toolboxErrorMessages['odataUnsupportedType']['replace']('{0}',_0x3b8c9e));case fileExtensionsWithoutDot['json']:throw createError(toolboxErrorMessages['odataUnsupportedType']['replace']('{0}',_0x3b8c9e));case columnDataTypes['custom']:throw createError(toolboxErrorMessages['odataUnsupportedType']['replace']('{0}',_0x3b8c9e));case columnDataTypes['buffer']:throw createError(toolboxErrorMessages['odataUnsupportedType']['replace']('{0}',_0x3b8c9e));default:throw createError(toolboxErrorMessages['odataUnsupportedType']['replace']('{0}',_0x3b8c9e));}return _0x3ad278;}__name(tryParseToType,'tryParseToType');function addExpressionByType(_0x526499,_0x1d7673,_0x4a3cee){const _0x28186d=getComparisonTypeFromOperation(_0x4a3cee),_0xfbe008=sql`${_0x526499}`;return _0x28186d(_0xfbe008,_0x1d7673);}__name(addExpressionByType,'addExpressionByType');

export { getFilterValue, tryFilter };
