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

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

        const notifications_preferences = await db.notifications_preferences.create(
            {
                id: data.id || undefined,
        
        dashboard_enabled: data.dashboard_enabled
        ||
        false
        
            ,
            
        email_enabled: data.email_enabled
        ||
        false
        
            ,
            
        sms_enabled: data.sms_enabled
        ||
        false
        
            ,
            
        whatsapp_enabled: data.whatsapp_enabled
        ||
        false
        
            ,
            
        remind_days_before: data.remind_days_before
        ||
        null
            ,
            
        escalate_after_days_overdue: data.escalate_after_days_overdue
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await notifications_preferences.setCompany( data.company || null, {
            transaction,
        });
        
        await notifications_preferences.setUser( data.user || null, {
            transaction,
        });
        
        await notifications_preferences.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return notifications_preferences;
    }
    

    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 notifications_preferencesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                dashboard_enabled: item.dashboard_enabled
            ||
            false
        
            ,
            
                email_enabled: item.email_enabled
            ||
            false
        
            ,
            
                sms_enabled: item.sms_enabled
            ||
            false
        
            ,
            
                whatsapp_enabled: item.whatsapp_enabled
            ||
            false
        
            ,
            
                remind_days_before: item.remind_days_before
            ||
            null
            ,
            
                escalate_after_days_overdue: item.escalate_after_days_overdue
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return notifications_preferences;
    }

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


        

        const updatePayload = {};
        
        if (data.dashboard_enabled !== undefined) updatePayload.dashboard_enabled = data.dashboard_enabled;
        
        
        if (data.email_enabled !== undefined) updatePayload.email_enabled = data.email_enabled;
        
        
        if (data.sms_enabled !== undefined) updatePayload.sms_enabled = data.sms_enabled;
        
        
        if (data.whatsapp_enabled !== undefined) updatePayload.whatsapp_enabled = data.whatsapp_enabled;
        
        
        if (data.remind_days_before !== undefined) updatePayload.remind_days_before = data.remind_days_before;
        
        
        if (data.escalate_after_days_overdue !== undefined) updatePayload.escalate_after_days_overdue = data.escalate_after_days_overdue;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await notifications_preferences.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await notifications_preferences.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await notifications_preferences.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return notifications_preferences;
    }

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

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

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


        return notifications_preferences;
    }

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

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

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

        await notifications_preferences.destroy({
            transaction
        });

        return notifications_preferences;
    }

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

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

        if (!notifications_preferences) {
            return notifications_preferences;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await notifications_preferences.getCompany({
            transaction
        });
        
        
        output.user = await notifications_preferences.getUser({
            transaction
        });
        
        
        output.organizations = await notifications_preferences.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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              company_name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            

            
            

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

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

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

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

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

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

            
            if (filter.dashboard_enabled) {
                where = {
                    ...where,
                dashboard_enabled: filter.dashboard_enabled,
            };
            }
            
            if (filter.email_enabled) {
                where = {
                    ...where,
                email_enabled: filter.email_enabled,
            };
            }
            
            if (filter.sms_enabled) {
                where = {
                    ...where,
                sms_enabled: filter.sms_enabled,
            };
            }
            
            if (filter.whatsapp_enabled) {
                where = {
                    ...where,
                whatsapp_enabled: filter.whatsapp_enabled,
            };
            }
            


      

      

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

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

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

    
};

