
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
            ,
            
        title: data.title
        ||
        null
            ,
            
        body: data.body
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        created_at_time: data.created_at_time
        ||
        null
            ,
            
        shown_at: data.shown_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await alerts.setCreator( data.creator || null, {
            transaction,
        });
        
        await alerts.setAlert_profile( data.alert_profile || null, {
            transaction,
        });
        
        await alerts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.alerts.getTableName(),
                belongsToColumn: 'media_images',
                belongsToId: alerts.id,
            },
            data.media_images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.alerts.getTableName(),
                belongsToColumn: 'sound_files',
                belongsToId: alerts.id,
            },
            data.sound_files,
            options,
        );
        

        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
            ,
            
                title: item.title
            ||
            null
            ,
            
                body: item.body
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                created_at_time: item.created_at_time
            ||
            null
            ,
            
                shown_at: item.shown_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
        
        for (let i = 0; i < alerts.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.alerts.getTableName(),
                    belongsToColumn: 'media_images',
                    belongsToId: alerts[i].id,
                },
                data[i].media_images,
                options,
            );
        }
        
        for (let i = 0; i < alerts.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.alerts.getTableName(),
                    belongsToColumn: 'sound_files',
                    belongsToId: alerts[i].id,
                },
                data[i].sound_files,
                options,
            );
        }
        

        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.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.body !== undefined) updatePayload.body = data.body;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.created_at_time !== undefined) updatePayload.created_at_time = data.created_at_time;
        
        
        if (data.shown_at !== undefined) updatePayload.shown_at = data.shown_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.creator !== undefined) {
            await alerts.setCreator(
              
              data.creator,
              
              { transaction }
            );
        }
        
        if (data.alert_profile !== undefined) {
            await alerts.setAlert_profile(
              
              data.alert_profile,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await alerts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.alerts.getTableName(),
                belongsToColumn: 'media_images',
                belongsToId: alerts.id,
            },
            data.media_images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.alerts.getTableName(),
                belongsToColumn: 'sound_files',
                belongsToId: alerts.id,
            },
            data.sound_files,
            options,
        );
        

        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.creator = await alerts.getCreator({
            transaction
        });
        
        
        output.alert_profile = await alerts.getAlert_profile({
            transaction
        });
        
        
        output.media_images = await alerts.getMedia_images({
            transaction
        });
        
        
        output.sound_files = await alerts.getSound_files({
            transaction
        });
        
        
        output.organizations = await alerts.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.creator_profiles,
        as: 'creator',
        
        where: filter.creator ? {
          [Op.or]: [
            { id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
            {
              handle: {
                [Op.or]: filter.creator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



      {
        model: db.file,
        as: 'media_images',
      },

      {
        model: db.file,
        as: 'sound_files',
      },

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alerts',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alerts',
                        'body',
                        filter.body,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alerts',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    shown_at: {
                    ...where.shown_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.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.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',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

