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

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

        const ai_monitoring_rules = await db.ai_monitoring_rules.create(
            {
                id: data.id || undefined,
        
        rule_name: data.rule_name
        ||
        null
            ,
            
        rule_type: data.rule_type
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        enabled: data.enabled
        ||
        false
        
            ,
            
        rule_description: data.rule_description
        ||
        null
            ,
            
        threshold_value: data.threshold_value
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_monitoring_rules.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return ai_monitoring_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 ai_monitoring_rulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                rule_name: item.rule_name
            ||
            null
            ,
            
                rule_type: item.rule_type
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                enabled: item.enabled
            ||
            false
        
            ,
            
                rule_description: item.rule_description
            ||
            null
            ,
            
                threshold_value: item.threshold_value
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ai_monitoring_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 ai_monitoring_rules = await db.ai_monitoring_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.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.enabled !== undefined) updatePayload.enabled = data.enabled;
        
        
        if (data.rule_description !== undefined) updatePayload.rule_description = data.rule_description;
        
        
        if (data.threshold_value !== undefined) updatePayload.threshold_value = data.threshold_value;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.schools !== undefined) {
            await ai_monitoring_rules.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return ai_monitoring_rules;
    }

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

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

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


        return ai_monitoring_rules;
    }

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

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

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

        await ai_monitoring_rules.destroy({
            transaction
        });

        return ai_monitoring_rules;
    }

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

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

        if (!ai_monitoring_rules) {
            return ai_monitoring_rules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.schools = await ai_monitoring_rules.getSchools({
            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 userSchools = (user && user.schools?.id) || null;
        

        
        if (userSchools) {
            if (options?.currentUser?.schoolsId) {
                where.schoolsId = options.currentUser.schoolsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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



    ];

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

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

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    threshold_value: {
                    ...where.threshold_value,
                            [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.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            
            if (filter.enabled) {
                where = {
                    ...where,
                enabled: filter.enabled,
            };
            }
            


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

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

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

        const records = await db.ai_monitoring_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,
        }));
    }

    
};

