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

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

        const alert_profiles = await db.alert_profiles.create(
            {
                id: data.id || undefined,
        
        profile_name: data.profile_name
        ||
        null
            ,
            
        brand_primary_hex: data.brand_primary_hex
        ||
        null
            ,
            
        brand_accent_hex: data.brand_accent_hex
        ||
        null
            ,
            
        animation_style: data.animation_style
        ||
        null
            ,
            
        tts_enabled: data.tts_enabled
        ||
        false
        
            ,
            
        tts_voice: data.tts_voice
        ||
        null
            ,
            
        template_style: data.template_style
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await alert_profiles.setOwner_user( data.owner_user || null, {
            transaction,
        });
        
        await alert_profiles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return alert_profiles;
    }
    

    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_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                profile_name: item.profile_name
            ||
            null
            ,
            
                brand_primary_hex: item.brand_primary_hex
            ||
            null
            ,
            
                brand_accent_hex: item.brand_accent_hex
            ||
            null
            ,
            
                animation_style: item.animation_style
            ||
            null
            ,
            
                tts_enabled: item.tts_enabled
            ||
            false
        
            ,
            
                tts_voice: item.tts_voice
            ||
            null
            ,
            
                template_style: item.template_style
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < alert_profiles.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.alert_profiles.getTableName(),
                    belongsToColumn: 'default_sound_files',
                    belongsToId: alert_profiles[i].id,
                },
                data[i].default_sound_files,
                options,
            );
        }
        

        return alert_profiles;
    }

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


        

        const updatePayload = {};
        
        if (data.profile_name !== undefined) updatePayload.profile_name = data.profile_name;
        
        
        if (data.brand_primary_hex !== undefined) updatePayload.brand_primary_hex = data.brand_primary_hex;
        
        
        if (data.brand_accent_hex !== undefined) updatePayload.brand_accent_hex = data.brand_accent_hex;
        
        
        if (data.animation_style !== undefined) updatePayload.animation_style = data.animation_style;
        
        
        if (data.tts_enabled !== undefined) updatePayload.tts_enabled = data.tts_enabled;
        
        
        if (data.tts_voice !== undefined) updatePayload.tts_voice = data.tts_voice;
        
        
        if (data.template_style !== undefined) updatePayload.template_style = data.template_style;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner_user !== undefined) {
            await alert_profiles.setOwner_user(
              
              data.owner_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await alert_profiles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return alert_profiles;
    }

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

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

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


        return alert_profiles;
    }

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

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

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

        await alert_profiles.destroy({
            transaction
        });

        return alert_profiles;
    }

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

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

        if (!alert_profiles) {
            return alert_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.alerts_alert_profile = await alert_profiles.getAlerts_alert_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner_user = await alert_profiles.getOwner_user({
            transaction
        });
        
        
        output.default_sound_files = await alert_profiles.getDefault_sound_files({
            transaction
        });
        
        
        output.organizations = await alert_profiles.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: 'owner_user',
        
        where: filter.owner_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.profile_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alert_profiles',
                        'profile_name',
                        filter.profile_name,
                    ),
                };
            }
            
            if (filter.brand_primary_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alert_profiles',
                        'brand_primary_hex',
                        filter.brand_primary_hex,
                    ),
                };
            }
            
            if (filter.brand_accent_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alert_profiles',
                        'brand_accent_hex',
                        filter.brand_accent_hex,
                    ),
                };
            }
            
            if (filter.tts_voice) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alert_profiles',
                        'tts_voice',
                        filter.tts_voice,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.animation_style) {
                where = {
                    ...where,
                animation_style: filter.animation_style,
            };
            }
            
            if (filter.tts_enabled) {
                where = {
                    ...where,
                tts_enabled: filter.tts_enabled,
            };
            }
            
            if (filter.template_style) {
                where = {
                    ...where,
                template_style: filter.template_style,
            };
            }
            


      

      
      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.alert_profiles.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_profiles',
                        'profile_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

