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

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

        const notification_preferences = await db.notification_preferences.create(
            {
                id: data.id || undefined,
        
        email_enabled: data.email_enabled
        ||
        false
        
            ,
            
        push_enabled: data.push_enabled
        ||
        false
        
            ,
            
        telegram_enabled: data.telegram_enabled
        ||
        false
        
            ,
            
        sms_enabled: data.sms_enabled
        ||
        false
        
            ,
            
        in_app_enabled: data.in_app_enabled
        ||
        false
        
            ,
            
        release_updates_enabled: data.release_updates_enabled
        ||
        false
        
            ,
            
        finance_updates_enabled: data.finance_updates_enabled
        ||
        false
        
            ,
            
        playlist_updates_enabled: data.playlist_updates_enabled
        ||
        false
        
            ,
            
        marketing_updates_enabled: data.marketing_updates_enabled
        ||
        false
        
            ,
            
        quiet_hours: data.quiet_hours
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return notification_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 notification_preferencesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                email_enabled: item.email_enabled
            ||
            false
        
            ,
            
                push_enabled: item.push_enabled
            ||
            false
        
            ,
            
                telegram_enabled: item.telegram_enabled
            ||
            false
        
            ,
            
                sms_enabled: item.sms_enabled
            ||
            false
        
            ,
            
                in_app_enabled: item.in_app_enabled
            ||
            false
        
            ,
            
                release_updates_enabled: item.release_updates_enabled
            ||
            false
        
            ,
            
                finance_updates_enabled: item.finance_updates_enabled
            ||
            false
        
            ,
            
                playlist_updates_enabled: item.playlist_updates_enabled
            ||
            false
        
            ,
            
                marketing_updates_enabled: item.marketing_updates_enabled
            ||
            false
        
            ,
            
                quiet_hours: item.quiet_hours
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.email_enabled !== undefined) updatePayload.email_enabled = data.email_enabled;
        
        
        if (data.push_enabled !== undefined) updatePayload.push_enabled = data.push_enabled;
        
        
        if (data.telegram_enabled !== undefined) updatePayload.telegram_enabled = data.telegram_enabled;
        
        
        if (data.sms_enabled !== undefined) updatePayload.sms_enabled = data.sms_enabled;
        
        
        if (data.in_app_enabled !== undefined) updatePayload.in_app_enabled = data.in_app_enabled;
        
        
        if (data.release_updates_enabled !== undefined) updatePayload.release_updates_enabled = data.release_updates_enabled;
        
        
        if (data.finance_updates_enabled !== undefined) updatePayload.finance_updates_enabled = data.finance_updates_enabled;
        
        
        if (data.playlist_updates_enabled !== undefined) updatePayload.playlist_updates_enabled = data.playlist_updates_enabled;
        
        
        if (data.marketing_updates_enabled !== undefined) updatePayload.marketing_updates_enabled = data.marketing_updates_enabled;
        
        
        if (data.quiet_hours !== undefined) updatePayload.quiet_hours = data.quiet_hours;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return notification_preferences;
    }

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

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

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


        return notification_preferences;
    }

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

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

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

        await notification_preferences.destroy({
            transaction
        });

        return notification_preferences;
    }

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

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

        if (!notification_preferences) {
            return notification_preferences;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await notification_preferences.getUser({
            transaction
        });
        
        
        output.organizations = await notification_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.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.quiet_hours) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'notification_preferences',
                        'quiet_hours',
                        filter.quiet_hours,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.email_enabled) {
                where = {
                    ...where,
                email_enabled: filter.email_enabled,
            };
            }
            
            if (filter.push_enabled) {
                where = {
                    ...where,
                push_enabled: filter.push_enabled,
            };
            }
            
            if (filter.telegram_enabled) {
                where = {
                    ...where,
                telegram_enabled: filter.telegram_enabled,
            };
            }
            
            if (filter.sms_enabled) {
                where = {
                    ...where,
                sms_enabled: filter.sms_enabled,
            };
            }
            
            if (filter.in_app_enabled) {
                where = {
                    ...where,
                in_app_enabled: filter.in_app_enabled,
            };
            }
            
            if (filter.release_updates_enabled) {
                where = {
                    ...where,
                release_updates_enabled: filter.release_updates_enabled,
            };
            }
            
            if (filter.finance_updates_enabled) {
                where = {
                    ...where,
                finance_updates_enabled: filter.finance_updates_enabled,
            };
            }
            
            if (filter.playlist_updates_enabled) {
                where = {
                    ...where,
                playlist_updates_enabled: filter.playlist_updates_enabled,
            };
            }
            
            if (filter.marketing_updates_enabled) {
                where = {
                    ...where,
                marketing_updates_enabled: filter.marketing_updates_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.notification_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(
                        'notification_preferences',
                        'quiet_hours',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

