// exports.SearchFilter = (search = '', fields = []) => {
//     if (!search || fields.length === 0) return {};

//     return {
//         OR: fields.map((field) => ({
//             [field]: {
//                 contains: search,
//                 mode: 'insensitive'
//             }
//         }))
//     };
// };

// exports.SearchFilter = (search = '', fields = []) => {
//     if (!search || fields.length === 0) return {};

//     const or = [];

//     for (const field of fields) {
//         const parts = field.split('.');
//         if (parts.length === 1) {
//             or.push({
//                 [field]: {
//                     contains: search,
//                     mode: 'insensitive',
//                 },
//             });
//         } else if (parts.length === 2) {
//             const [relation, subfield] = parts;
//             or.push({
//                 [relation]: {
//                     is: {
//                         [subfield]: {
//                             contains: search,
//                             mode: 'insensitive',
//                         }
//                     }
//                 }
//             });
//         }
//     }

//     return { OR: or };
// };

exports.SearchFilter = (search = '', fields = [], arrayRelations = []) => {
    if (!search || fields.length === 0) return {};

    const buildNestedFilter = (parts, value) => {
        if (parts.length === 1) {
            return {
                [parts[0]]: {
                    contains: value,
                    mode: 'insensitive',
                },
            };
        }

        const [current, ...rest] = parts;

        const nested = buildNestedFilter(rest, value);

        // Jika current adalah array relation
        if (arrayRelations.includes(current)) {
            return {
                [current]: {
                    some: nested,
                },
            };
        } else {
            return {
                [current]: {
                    is: nested,
                },
            };
        }
    };

    const or = fields.map(field => {
        const parts = field.split('.');
        return buildNestedFilter(parts, search);
    });

    return { OR: or };
};