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

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

        const alerts = await db.alerts.create(
            {
                id: data.id || undefined,
        
        alert_type: data.alert_type
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        title_text: data.title_text
        ||
        null
            ,
            
        details: data.details
        ||
        null
            ,
            
        triggered_at: data.triggered_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        acknowledged_at: data.acknowledged_at
        ||
        null
            ,
            
        resolved_at: data.resolved_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await alerts.setPatient( data.patient || null, {
            transaction,
        });
        
        await alerts.setDevice( data.device || null, {
            transaction,
        });
        
        await alerts.setTrigger_event( data.trigger_event || null, {
            transaction,
        });
        
        await alerts.setAssigned_to_user( data.assigned_to_user || null, {
            transaction,
        });
        
        await alerts.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return 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 alertsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                alert_type: item.alert_type
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                title_text: item.title_text
            ||
            null
            ,
            
                details: item.details
            ||
            null
            ,
            
                triggered_at: item.triggered_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                acknowledged_at: item.acknowledged_at
            ||
            null
            ,
            
                resolved_at: item.resolved_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return alerts;
    }

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


        

        const updatePayload = {};
        
        if (data.alert_type !== undefined) updatePayload.alert_type = data.alert_type;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
        
        
        if (data.details !== undefined) updatePayload.details = data.details;
        
        
        if (data.triggered_at !== undefined) updatePayload.triggered_at = data.triggered_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.acknowledged_at !== undefined) updatePayload.acknowledged_at = data.acknowledged_at;
        
        
        if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await alerts.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.device !== undefined) {
            await alerts.setDevice(
              
              data.device,
              
              { transaction }
            );
        }
        
        if (data.trigger_event !== undefined) {
            await alerts.setTrigger_event(
              
              data.trigger_event,
              
              { transaction }
            );
        }
        
        if (data.assigned_to_user !== undefined) {
            await alerts.setAssigned_to_user(
              
              data.assigned_to_user,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await alerts.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return alerts;
    }

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

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

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


        return alerts;
    }

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

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

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

        await alerts.destroy({
            transaction
        });

        return alerts;
    }

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

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

        if (!alerts) {
            return alerts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.alert_notifications_alert = await alerts.getAlert_notifications_alert({
            transaction
        });
        
        
        
        
        
        
        
        
        output.patient = await alerts.getPatient({
            transaction
        });
        
        
        output.device = await alerts.getDevice({
            transaction
        });
        
        
        output.trigger_event = await alerts.getTrigger_event({
            transaction
        });
        
        
        output.assigned_to_user = await alerts.getAssigned_to_user({
            transaction
        });
        
        
        output.accounts = await alerts.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.iot_devices,
        as: 'device',
        
        where: filter.device ? {
          [Op.or]: [
            { id: { [Op.in]: filter.device.split('|').map(term => Utils.uuid(term)) } },
            {
              device_label: {
                [Op.or]: filter.device.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.users,
        as: 'assigned_to_user',
        
        where: filter.assigned_to_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.assigned_to_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.assigned_to_user.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.title_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alerts',
                        'title_text',
                        filter.title_text,
                    ),
                };
            }
            
            if (filter.details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alerts',
                        'details',
                        filter.details,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      

      

      

      

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

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

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

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

    
};

