
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 Geofence_alertsDBApi {
    

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

        const geofence_alerts = await db.geofence_alerts.create(
            {
                id: data.id || undefined,
        
        distance_meters: data.distance_meters
        ||
        null
            ,
            
        latitude: data.latitude
        ||
        null
            ,
            
        longitude: data.longitude
        ||
        null
            ,
            
        alert_time: data.alert_time
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        is_acknowledged: data.is_acknowledged
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await geofence_alerts.setRestaurant( data.restaurant || null, {
            transaction,
        });
        
        await geofence_alerts.setStaff_user( data.staff_user || null, {
            transaction,
        });
        
        await geofence_alerts.setAcknowledged_by_user( data.acknowledged_by_user || null, {
            transaction,
        });
        

        

        

        return geofence_alerts;
    }
    

    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 geofence_alertsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                distance_meters: item.distance_meters
            ||
            null
            ,
            
                latitude: item.latitude
            ||
            null
            ,
            
                longitude: item.longitude
            ||
            null
            ,
            
                alert_time: item.alert_time
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                is_acknowledged: item.is_acknowledged
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return geofence_alerts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.distance_meters !== undefined) updatePayload.distance_meters = data.distance_meters;
        
        
        if (data.latitude !== undefined) updatePayload.latitude = data.latitude;
        
        
        if (data.longitude !== undefined) updatePayload.longitude = data.longitude;
        
        
        if (data.alert_time !== undefined) updatePayload.alert_time = data.alert_time;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.is_acknowledged !== undefined) updatePayload.is_acknowledged = data.is_acknowledged;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.restaurant !== undefined) {
            await geofence_alerts.setRestaurant(
              
              data.restaurant,
              
              { transaction }
            );
        }
        
        if (data.staff_user !== undefined) {
            await geofence_alerts.setStaff_user(
              
              data.staff_user,
              
              { transaction }
            );
        }
        
        if (data.acknowledged_by_user !== undefined) {
            await geofence_alerts.setAcknowledged_by_user(
              
              data.acknowledged_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return geofence_alerts;
    }

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

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

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


        return geofence_alerts;
    }

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

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

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

        await geofence_alerts.destroy({
            transaction
        });

        return geofence_alerts;
    }

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

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

        if (!geofence_alerts) {
            return geofence_alerts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.restaurant = await geofence_alerts.getRestaurant({
            transaction
        });
        
        
        output.staff_user = await geofence_alerts.getStaff_user({
            transaction
        });
        
        
        output.acknowledged_by_user = await geofence_alerts.getAcknowledged_by_user({
            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.restaurants,
        as: 'restaurant',
        
        where: filter.restaurant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.restaurant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.restaurant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            
            if (filter.is_acknowledged) {
                where = {
                    ...where,
                is_acknowledged: filter.is_acknowledged,
            };
            }
            


      

      

      



            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.geofence_alerts.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(
                        'geofence_alerts',
                        'severity',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

