
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,
        
        channel: data.channel
        ||
        null
            ,
            
        likes_enabled: data.likes_enabled
        ||
        false
        
            ,
            
        comments_enabled: data.comments_enabled
        ||
        false
        
            ,
            
        tags_enabled: data.tags_enabled
        ||
        false
        
            ,
            
        mentions_enabled: data.mentions_enabled
        ||
        false
        
            ,
            
        shares_enabled: data.shares_enabled
        ||
        false
        
            ,
            
        uploads_enabled: data.uploads_enabled
        ||
        false
        
            ,
            
            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,
                
                channel: item.channel
            ||
            null
            ,
            
                likes_enabled: item.likes_enabled
            ||
            false
        
            ,
            
                comments_enabled: item.comments_enabled
            ||
            false
        
            ,
            
                tags_enabled: item.tags_enabled
            ||
            false
        
            ,
            
                mentions_enabled: item.mentions_enabled
            ||
            false
        
            ,
            
                shares_enabled: item.shares_enabled
            ||
            false
        
            ,
            
                uploads_enabled: item.uploads_enabled
            ||
            false
        
            ,
            
            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.channel !== undefined) updatePayload.channel = data.channel;
        
        
        if (data.likes_enabled !== undefined) updatePayload.likes_enabled = data.likes_enabled;
        
        
        if (data.comments_enabled !== undefined) updatePayload.comments_enabled = data.comments_enabled;
        
        
        if (data.tags_enabled !== undefined) updatePayload.tags_enabled = data.tags_enabled;
        
        
        if (data.mentions_enabled !== undefined) updatePayload.mentions_enabled = data.mentions_enabled;
        
        
        if (data.shares_enabled !== undefined) updatePayload.shares_enabled = data.shares_enabled;
        
        
        if (data.uploads_enabled !== undefined) updatePayload.uploads_enabled = data.uploads_enabled;
        
        
        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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.channel) {
                where = {
                    ...where,
                channel: filter.channel,
            };
            }
            
            if (filter.likes_enabled) {
                where = {
                    ...where,
                likes_enabled: filter.likes_enabled,
            };
            }
            
            if (filter.comments_enabled) {
                where = {
                    ...where,
                comments_enabled: filter.comments_enabled,
            };
            }
            
            if (filter.tags_enabled) {
                where = {
                    ...where,
                tags_enabled: filter.tags_enabled,
            };
            }
            
            if (filter.mentions_enabled) {
                where = {
                    ...where,
                mentions_enabled: filter.mentions_enabled,
            };
            }
            
            if (filter.shares_enabled) {
                where = {
                    ...where,
                shares_enabled: filter.shares_enabled,
            };
            }
            
            if (filter.uploads_enabled) {
                where = {
                    ...where,
                uploads_enabled: filter.uploads_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',
                        'channel',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

