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

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

        const alert_notifications = await db.alert_notifications.create(
            {
                id: data.id || undefined,
        
        channel: data.channel
        ||
        null
            ,
            
        sent_at: data.sent_at
        ||
        null
            ,
            
        delivery_status: data.delivery_status
        ||
        null
            ,
            
        provider_message_id: data.provider_message_id
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await alert_notifications.setAlert( data.alert || null, {
            transaction,
        });
        
        await alert_notifications.setRecipient_user( data.recipient_user || null, {
            transaction,
        });
        
        await alert_notifications.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return alert_notifications;
    }
    

    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 alert_notificationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                channel: item.channel
            ||
            null
            ,
            
                sent_at: item.sent_at
            ||
            null
            ,
            
                delivery_status: item.delivery_status
            ||
            null
            ,
            
                provider_message_id: item.provider_message_id
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return alert_notifications;
    }

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


        

        const updatePayload = {};
        
        if (data.channel !== undefined) updatePayload.channel = data.channel;
        
        
        if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
        
        
        if (data.delivery_status !== undefined) updatePayload.delivery_status = data.delivery_status;
        
        
        if (data.provider_message_id !== undefined) updatePayload.provider_message_id = data.provider_message_id;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.alert !== undefined) {
            await alert_notifications.setAlert(
              
              data.alert,
              
              { transaction }
            );
        }
        
        if (data.recipient_user !== undefined) {
            await alert_notifications.setRecipient_user(
              
              data.recipient_user,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await alert_notifications.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return alert_notifications;
    }

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

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

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


        return alert_notifications;
    }

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

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

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

        await alert_notifications.destroy({
            transaction
        });

        return alert_notifications;
    }

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

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

        if (!alert_notifications) {
            return alert_notifications;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.alert = await alert_notifications.getAlert({
            transaction
        });
        
        
        output.recipient_user = await alert_notifications.getRecipient_user({
            transaction
        });
        
        
        output.accounts = await alert_notifications.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.alerts,
        as: 'alert',
        
        where: filter.alert ? {
          [Op.or]: [
            { id: { [Op.in]: filter.alert.split('|').map(term => Utils.uuid(term)) } },
            {
              title_text: {
                [Op.or]: filter.alert.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

            
            

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

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

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

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

            
            if (filter.channel) {
                where = {
                    ...where,
                channel: filter.channel,
            };
            }
            
            if (filter.delivery_status) {
                where = {
                    ...where,
                delivery_status: filter.delivery_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.alert_notifications.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(
                        'alert_notifications',
                        'delivery_status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

