// /* eslint-disable no-lonely-if */
// import {
//   escapeForPostgres,
//   filterModelByOperator,
//   transformModelOperatorToSqlOperator,
// } from '@pjap/shared/data-grid-premium/util';
// import { isArray } from 'lodash';

// /**
//  * Configuration object for customizing how individual fields are processed during search
//  *
//  * @typedef {Object} FieldConfig
//  * @property {string} [type] - Data type of the field ('string', 'date', 'number', etc.)
//  *                            Used for applying appropriate transformations and SQL operations
//  *
//  * @property {function} [transformValue] - Custom function to transform field values before SQL generation
//  *                                       Signature: (value, modelOperator) => transformedValue
//  *                                       Example: Convert date formats, escape special characters
//  *
//  * @property {function} [transformField] - Custom function to transform field names
//  *                                       Signature: (fieldName, value) => transformedFieldName
//  *                                       Example: Map UI field names to database column names
//  *
//  * @property {string|string[]} [fieldMapping] - Direct mapping to different database field name(s)
//  *                                            String: Maps to single field
//  *                                            Array: Maps to multiple fields (OR condition)
//  *
//  * @property {function|string} [operator] - Custom operator transformation
//  *                                        Function: (sqlOperator, originalOperator, value) => newOperator
//  *                                        String: Fixed operator to use (e.g., 'LIKE', 'IN')
//  *
//  * @property {function} [additionalQuery] - Generates additional SQL conditions for complex searches
//  *                                        Signature: (value) => additionalSqlCondition
//  *                                        Example: Add related table joins or complex WHERE clauses
//  *
//  * @property {string} [additionalQueryLogicOperator='AND'] - Logic operator ('AND' or 'OR') to combine
//  *                                                          main query with additional query
//  */

// /**
//  * Configuration options for the useAdvancedSearch hook
//  *
//  * @typedef {Object} UseAdvancedSearchOptions
//  * @property {Object.<string, FieldConfig>} [fieldConfigs] - Field-specific configurations
//  *                                                          Key: field name, Value: FieldConfig object
//  *
//  * @property {function} [globalValueTransform] - Global transformation applied to all field values
//  *                                             Signature: (fieldName, value) => transformedValue
//  *                                             Applied when no field-specific transform exists
//  *
//  * @property {function} [globalFieldTransform] - Global transformation applied to all field names
//  *                                             Signature: (fieldName) => transformedFieldName
//  *                                             Applied when no field-specific transform exists
//  *
//  * @property {Object.<string, string>} [defaultFieldTypes] - Default data types for fields
//  *                                                          Key: field name, Value: type string
//  *                                                          Used when field type not specified in fieldConfigs
//  */

// /**
//  * Advanced Search Hook
//  *
//  * Provides functionality to convert DataGrid Premium filter models into SQL WHERE clauses
//  * with extensive customization options for field transformations, value processing, and
//  * complex query generation.
//  *
//  * MAIN USE CASES:
//  * 1. Convert frontend filter UI state to backend SQL queries
//  * 2. Handle complex field mappings (UI field → database column)
//  * 3. Apply custom value transformations (dates, case sensitivity, escaping)
//  * 4. Generate complex queries with joins and additional conditions
//  *
//  * @param {UseAdvancedSearchOptions} options - Configuration options for customizing search behavior
//  * @returns {Object} Object containing the main query generation function
//  */
// const useAdvancedSearch = (options = {}) => {
//   // Extract configuration options with defaults
//   const {
//     fieldConfigs = {}, // Field-specific configurations
//     globalValueTransform, // Global value transformation function
//     globalFieldTransform, // Global field name transformation function
//     defaultFieldTypes = {}, // Default field type mappings
//   } = options;

//   /**
//    * Transform Field Values
//    *
//    * Applies transformations to field values based on priority:
//    * 1. Field-specific transformValue function (highest priority)
//    * 2. Global value transformation function
//    * 3. Built-in type-based transformations (lowest priority)
//    *
//    * BUILT-IN TRANSFORMATIONS:
//    * - 'date': Removes hyphens and underscores (2023-01-01 → 20230101)
//    * - 'string': Converts to lowercase and escapes for PostgreSQL
//    * - default: Returns value unchanged
//    *
//    * @param {string} field - The field name being processed
//    * @param {any} value - The original field value from the filter
//    * @param {string} modelOperator - The operator from the DataGrid model
//    * @returns {any} The transformed value ready for SQL generation
//    */
//   const transformValue = (field, value = '', modelOperator) => {
//     // Skip transformation for null/undefined values
//     // if (!value) return value;

//     // Priority 1: Field-specific transformation
//     if (fieldConfigs[field]?.transformValue) {
//       return fieldConfigs[field].transformValue(value, modelOperator);
//     }

//     // Priority 2: Global transformation
//     if (globalValueTransform) {
//       return globalValueTransform(field, value);
//     }

//     // Priority 3: Built-in type-based transformations
//     const fieldType = fieldConfigs[field]?.type || defaultFieldTypes[field] || 'string';

//     switch (fieldType) {
//       case 'date':
//         // Remove date separators for database storage format
//         return value.replace(/-/g, '').replace(/_/g, '');

//       case 'string':
//         // Convert to lowercase and escape special PostgreSQL characters
//         return escapeForPostgres(typeof value === 'string' ? value.toLowerCase() : value);

//       default:
//         // No transformation for other types (numbers, booleans, etc.)
//         return value;
//     }
//   };

//   /**
//    * Transform Field Names
//    *
//    * Maps UI field names to database column names with priority:
//    * 1. Direct fieldMapping configuration (highest priority)
//    * 2. Field-specific transformField function
//    * 3. Global field transformation function
//    * 4. Original field name (lowest priority)
//    *
//    * FIELD MAPPING EXAMPLES:
//    * - String mapping: "userName" → "user_name"
//    * - Array mapping: "fullName" → ["first_name", "last_name"] (creates OR condition)
//    *
//    * @param {string} field - The original field name from the UI
//    * @param {any} value - The field value (may influence transformation)
//    * @returns {string|string[]} The transformed field name(s) for database queries
//    */
//   const transformField = (field, value) => {
//     // Priority 1: Direct field mapping
//     if (fieldConfigs[field]?.fieldMapping) {
//       return fieldConfigs[field].fieldMapping;
//     }

//     // Priority 2: Field-specific transformation function
//     if (fieldConfigs[field]?.transformField) {
//       return fieldConfigs[field].transformField(field, value);
//     }

//     // Priority 3: Global field transformation
//     if (globalFieldTransform) {
//       return globalFieldTransform(field);
//     }

//     // Priority 4: Use original field name
//     return field;
//   };

//   /**
//    * Transform SQL Operators
//    *
//    * Converts DataGrid operators to appropriate SQL operators with custom logic support.
//    * Allows field-specific operator overrides for special cases.
//    *
//    * OPERATOR EXAMPLES:
//    * - DataGrid "contains" → SQL "LIKE"
//    * - DataGrid "equals" → SQL "="
//    * - Custom: Force "ILIKE" for case-insensitive searches
//    *
//    * @param {string} field - The field name being processed
//    * @param {string} operator - The original operator from DataGrid
//    * @param {any} value - The field value (may influence operator choice)
//    * @returns {string} The SQL operator to use in the query
//    */
//   const transformOperator = (field, operator, value) => {
//     // Check for field-specific operator configuration
//     if (fieldConfigs[field]?.operator) {
//       // If operator config is a function, call it with context
//       if (typeof fieldConfigs[field].operator === 'function') {
//         console.log('ini kesini lagi yah');
//         return fieldConfigs[field].operator(
//           transformModelOperatorToSqlOperator(operator), // Converted SQL operator
//           operator, // Original DataGrid operator
//           value // Field value for context
//         );
//       }
//         console.log('ini keskip berarti');

//       // If operator config is a string, use it directly
//       return fieldConfigs[field].operator;
//     }

//     // Use default operator transformation
//     return operator;
//   };

//   const buildQuery = (item, transformedField, fieldValue) => {
//     // Transform the field value with all configured transformations
//     const value = transformValue(item.columnField, fieldValue, item.operatorValue);
//     // Transform the operator for this field
//     const operator = transformOperator(item.columnField, item.operatorValue, fieldValue);
//     console.log('ini operator datagrid', operator);
//     // Get the field type for proper SQL generation
//     const fieldType =
//       fieldConfigs[item.columnField]?.type || defaultFieldTypes[item.columnField] || 'string';

//     let baseQuery;

//     // Handle multiple field mappings (when field is an array)
//     if (Array.isArray(transformedField)) {
//       // Check if we have multiple values for multiple fields
//       if (typeof value === 'object') {
//         // Map each field to its corresponding value (parallel arrays)
//         // Example: fields=["first_name", "last_name"], values={0: "John", 1: "Doe"}
//         // Result: first_name = 'John' AND last_name = 'Doe'
//         baseQuery = transformedField
//           .map((f, index) => {
//             const newValue = Object.values(value)[index];
//             return filterModelByOperator(f, operator, newValue, fieldType);
//           })
//           .join(' AND ');
//       } else {
//         // Same value applied to all fields (OR condition)
//         // Example: fields=["first_name", "last_name"], value="John"
//         // Result: first_name LIKE '%John%' OR last_name LIKE '%John%'
//         baseQuery = transformedField
//           .map((f) => filterModelByOperator(f, operator, value, fieldType))
//           .join(' OR ');
//       }
//     } else {
//       // Single field mapping

//       // Handle custom operators that need special SQL construction
//       if (fieldConfigs[item.columnField]?.operator) {
//         baseQuery = `LOWER("${transformedField}") ${operator} ${value}`;
//       } else {
//         baseQuery = filterModelByOperator(transformedField, operator, value, fieldType);
//       }
//     }

//     // Handle additional query conditions (for complex search scenarios)
//     if (fieldConfigs[item.columnField]?.additionalQuery) {
//       // Generate additional SQL condition
//       const additionalQuery = fieldConfigs[item.columnField].additionalQuery(fieldValue);

//       // Get the logic operator for combining base and additional queries
//       const logicOperator = fieldConfigs[item.columnField]?.additionalQueryLogicOperator || 'AND';

//       // Combine base and additional queries if additional query exists
//       if (additionalQuery) {
//         return `(${[baseQuery, additionalQuery].filter(Boolean).join(` ${logicOperator} `)})`;
//       }
//     }

//     return baseQuery;
//   };

//   /**
//    * Generate SQL Query from DataGrid Filter Model
//    *
//    * Main function that converts a DataGrid Premium filter model into a SQL WHERE clause.
//    * Handles complex scenarios including:
//    * - Multiple field mappings (OR conditions)
//    * - Custom operators and value transformations
//    * - Additional query conditions with configurable logic operators
//    * - Proper SQL escaping and type handling
//    *
//    * FILTER MODEL STRUCTURE:
//    * {
//    *   items: [
//    *     {
//    *       columnField: "fieldName",
//    *       operatorValue: "contains",
//    *       value: "searchTerm"
//    *     }
//    *   ],
//    *   linkOperator: "AND" // or "OR"
//    * }
//    *
//    * @param {Object} model - The filter model from DataGrid Premium
//    * @param {Array} model.items - Array of individual filter conditions
//    * @param {string} model.linkOperator - Logic operator to combine multiple conditions ("AND" or "OR")
//    * @returns {string} Generated SQL WHERE clause (without the "WHERE" keyword)
//    */
//   const generateSqlQueryByDatagridPremiumModel = (model) => {
//     // Process each filter item in the model
//     const advanced = model.items
//       ?.map((item) => {
//         // Transform the field name (UI → database column)
//         const field = transformField(item.columnField, item.value);
//         if (item.operatorValue === 'isAnyOf' && isArray(item.value)) {
//           if (item.value.length > 0) {
//             const query = item.value.map((v) => `${buildQuery(item, field, v)}`).join(' OR ');
//             return `(${query})`;
//           }
//           return '';
//         }

//         return buildQuery(item, field, item.value);
//       })
//       // Remove any empty/null queries
//       .filter(Boolean)
//       // Join all conditions with the model's link operator (AND/OR)
//       .join(` ${model.linkOperator} `);

//     return advanced;
//   };

//   // Return the main query generation function
//   return {
//     generateSqlQueryByDatagridPremiumModel,
//   };
// };

// export default useAdvancedSearch;
