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

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

        const geo_rules = await db.geo_rules.create(
            {
                id: data.id || undefined,
        
        rule_name: data.rule_name
        ||
        null
            ,
            
        rule_type: data.rule_type
        ||
        null
            ,
            
        center_latitude: data.center_latitude
        ||
        null
            ,
            
        center_longitude: data.center_longitude
        ||
        null
            ,
            
        radius_meters: data.radius_meters
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await geo_rules.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return geo_rules;
    }
    

    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 geo_rulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                rule_name: item.rule_name
            ||
            null
            ,
            
                rule_type: item.rule_type
            ||
            null
            ,
            
                center_latitude: item.center_latitude
            ||
            null
            ,
            
                center_longitude: item.center_longitude
            ||
            null
            ,
            
                radius_meters: item.radius_meters
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return geo_rules;
    }

    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 geo_rules = await db.geo_rules.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.rule_name !== undefined) updatePayload.rule_name = data.rule_name;
        
        
        if (data.rule_type !== undefined) updatePayload.rule_type = data.rule_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.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organizations !== undefined) {
            await geo_rules.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return geo_rules;
    }

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

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

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


        return geo_rules;
    }

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

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

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

        await geo_rules.destroy({
            transaction
        });

        return geo_rules;
    }

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

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

        if (!geo_rules) {
            return geo_rules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organizations = await geo_rules.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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



    ];

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

            
            if (filter.rule_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'geo_rules',
                        'rule_name',
                        filter.rule_name,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'geo_rules',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            
            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.rule_type) {
                where = {
                    ...where,
                rule_type: filter.rule_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


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

        where = {
          ...where,
          organizationsId: {[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.organizationsId;
        }
        

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

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

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

    
};

