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

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

        const geofences = await db.geofences.create(
            {
                id: data.id || undefined,
        
        geofence_name: data.geofence_name
        ||
        null
            ,
            
        shape_type: data.shape_type
        ||
        null
            ,
            
        center_latitude: data.center_latitude
        ||
        null
            ,
            
        center_longitude: data.center_longitude
        ||
        null
            ,
            
        radius_meters: data.radius_meters
        ||
        null
            ,
            
        polygon_points: data.polygon_points
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        alert_on: data.alert_on
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await geofences.setPatient( data.patient || null, {
            transaction,
        });
        
        await geofences.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return geofences;
    }
    

    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 geofencesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                geofence_name: item.geofence_name
            ||
            null
            ,
            
                shape_type: item.shape_type
            ||
            null
            ,
            
                center_latitude: item.center_latitude
            ||
            null
            ,
            
                center_longitude: item.center_longitude
            ||
            null
            ,
            
                radius_meters: item.radius_meters
            ||
            null
            ,
            
                polygon_points: item.polygon_points
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                alert_on: item.alert_on
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return geofences;
    }

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

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


        

        const updatePayload = {};
        
        if (data.geofence_name !== undefined) updatePayload.geofence_name = data.geofence_name;
        
        
        if (data.shape_type !== undefined) updatePayload.shape_type = data.shape_type;
        
        
        if (data.center_latitude !== undefined) updatePayload.center_latitude = data.center_latitude;
        
        
        if (data.center_longitude !== undefined) updatePayload.center_longitude = data.center_longitude;
        
        
        if (data.radius_meters !== undefined) updatePayload.radius_meters = data.radius_meters;
        
        
        if (data.polygon_points !== undefined) updatePayload.polygon_points = data.polygon_points;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.alert_on !== undefined) updatePayload.alert_on = data.alert_on;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await geofences.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await geofences.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return geofences;
    }

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

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

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


        return geofences;
    }

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

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

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

        await geofences.destroy({
            transaction
        });

        return geofences;
    }

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

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

        if (!geofences) {
            return geofences;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await geofences.getPatient({
            transaction
        });
        
        
        output.accounts = await geofences.getAccounts({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userAccounts = (user && user.accounts?.id) || null;
        

        
        if (userAccounts) {
            if (options?.currentUser?.accountsId) {
                where.accountsId = options.currentUser.accountsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

      {
        model: db.accounts,
        as: 'accounts',
        
      },



    ];

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

            
            if (filter.geofence_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'geofences',
                        'geofence_name',
                        filter.geofence_name,
                    ),
                };
            }
            
            if (filter.polygon_points) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'geofences',
                        'polygon_points',
                        filter.polygon_points,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.shape_type) {
                where = {
                    ...where,
                shape_type: filter.shape_type,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            
            if (filter.alert_on) {
                where = {
                    ...where,
                alert_on: filter.alert_on,
            };
            }
            


      

      
      if (filter.accounts) {
        const listItems = filter.accounts.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          accountsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.accountsId;
        }
        

        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.geofences.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

