
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Search_logsDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const search_logs = await db.search_logs.create(
            {
                id: data.id || undefined,
        
        query_text: data.query_text
        ||
        null
            ,
            
        search_latitude: data.search_latitude
        ||
        null
            ,
            
        search_longitude: data.search_longitude
        ||
        null
            ,
            
        radius_km: data.radius_km
        ||
        null
            ,
            
        searched_at: data.searched_at
        ||
        null
            ,
            
        results_count: data.results_count
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await search_logs.setUser( data.user || null, {
            transaction,
        });
        
        await search_logs.setCategory( data.category || null, {
            transaction,
        });
        

        

        

        return search_logs;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const search_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                query_text: item.query_text
            ||
            null
            ,
            
                search_latitude: item.search_latitude
            ||
            null
            ,
            
                search_longitude: item.search_longitude
            ||
            null
            ,
            
                radius_km: item.radius_km
            ||
            null
            ,
            
                searched_at: item.searched_at
            ||
            null
            ,
            
                results_count: item.results_count
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const search_logs = await db.search_logs.bulkCreate(search_logsData, { transaction });

        // For each item created, replace relation files
        

        return search_logs;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const search_logs = await db.search_logs.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.query_text !== undefined) updatePayload.query_text = data.query_text;
        
        
        if (data.search_latitude !== undefined) updatePayload.search_latitude = data.search_latitude;
        
        
        if (data.search_longitude !== undefined) updatePayload.search_longitude = data.search_longitude;
        
        
        if (data.radius_km !== undefined) updatePayload.radius_km = data.radius_km;
        
        
        if (data.searched_at !== undefined) updatePayload.searched_at = data.searched_at;
        
        
        if (data.results_count !== undefined) updatePayload.results_count = data.results_count;
        
        
        updatePayload.updatedById = currentUser.id;

        await search_logs.update(updatePayload, {transaction});

        
        
        if (data.user !== undefined) {
            await search_logs.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.category !== undefined) {
            await search_logs.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        

        
        

        

        return search_logs;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const search_logs = await db.search_logs.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of search_logs) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of search_logs) {
                await record.destroy({transaction});
            }
        });


        return search_logs;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const search_logs = await db.search_logs.findByPk(id, options);

        await search_logs.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await search_logs.destroy({
            transaction
        });

        return search_logs;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const search_logs = await db.search_logs.findOne(
            { where },
            { transaction },
        );

        if (!search_logs) {
            return search_logs;
        }

        const output = search_logs.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await search_logs.getUser({
            transaction
        });
        
        
        output.category = await search_logs.getCategory({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.place_categories,
        as: 'category',
        
        where: filter.category ? {
          [Op.or]: [
            { id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.query_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'search_logs',
                        'query_text',
                        filter.query_text,
                    ),
                };
            }
            

            
            

            
            if (filter.search_latitudeRange) {
                const [start, end] = filter.search_latitudeRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    search_latitude: {
                    ...where.search_latitude,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    search_latitude: {
                    ...where.search_latitude,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.search_longitudeRange) {
                const [start, end] = filter.search_longitudeRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    search_longitude: {
                    ...where.search_longitude,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    search_longitude: {
                    ...where.search_longitude,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.radius_kmRange) {
                const [start, end] = filter.radius_kmRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    radius_km: {
                    ...where.radius_km,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    radius_km: {
                    ...where.radius_km,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.searched_atRange) {
                const [start, end] = filter.searched_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    searched_at: {
                    ...where.searched_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    searched_at: {
                    ...where.searched_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.results_countRange) {
                const [start, end] = filter.results_countRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    results_count: {
                    ...where.results_count,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    results_count: {
                    ...where.results_count,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            


      

      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.search_logs.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'search_logs',
                        'query_text',
                        query,
                    ),
                ],
            };
        }

        const records = await db.search_logs.findAll({
            attributes: [ 'id', 'query_text' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['query_text', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.query_text,
        }));
    }

    
};

