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

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

        const user_settings = await db.user_settings.create(
            {
                id: data.id || undefined,
        
        time_zone: data.time_zone
        ||
        null
            ,
            
        locale: data.locale
        ||
        null
            ,
            
        theme: data.theme
        ||
        null
            ,
            
        default_entry_mode: data.default_entry_mode
        ||
        null
            ,
            
        voice_mode_enabled: data.voice_mode_enabled
        ||
        false
        
            ,
            
        preferred_voice: data.preferred_voice
        ||
        null
            ,
            
        speech_rate: data.speech_rate
        ||
        null
            ,
            
        speech_pitch: data.speech_pitch
        ||
        null
            ,
            
        safe_confirmations_enabled: data.safe_confirmations_enabled
        ||
        false
        
            ,
            
        auto_archive_days: data.auto_archive_days
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await user_settings.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return user_settings;
    }
    

    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 user_settingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                time_zone: item.time_zone
            ||
            null
            ,
            
                locale: item.locale
            ||
            null
            ,
            
                theme: item.theme
            ||
            null
            ,
            
                default_entry_mode: item.default_entry_mode
            ||
            null
            ,
            
                voice_mode_enabled: item.voice_mode_enabled
            ||
            false
        
            ,
            
                preferred_voice: item.preferred_voice
            ||
            null
            ,
            
                speech_rate: item.speech_rate
            ||
            null
            ,
            
                speech_pitch: item.speech_pitch
            ||
            null
            ,
            
                safe_confirmations_enabled: item.safe_confirmations_enabled
            ||
            false
        
            ,
            
                auto_archive_days: item.auto_archive_days
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return user_settings;
    }

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


        

        const updatePayload = {};
        
        if (data.time_zone !== undefined) updatePayload.time_zone = data.time_zone;
        
        
        if (data.locale !== undefined) updatePayload.locale = data.locale;
        
        
        if (data.theme !== undefined) updatePayload.theme = data.theme;
        
        
        if (data.default_entry_mode !== undefined) updatePayload.default_entry_mode = data.default_entry_mode;
        
        
        if (data.voice_mode_enabled !== undefined) updatePayload.voice_mode_enabled = data.voice_mode_enabled;
        
        
        if (data.preferred_voice !== undefined) updatePayload.preferred_voice = data.preferred_voice;
        
        
        if (data.speech_rate !== undefined) updatePayload.speech_rate = data.speech_rate;
        
        
        if (data.speech_pitch !== undefined) updatePayload.speech_pitch = data.speech_pitch;
        
        
        if (data.safe_confirmations_enabled !== undefined) updatePayload.safe_confirmations_enabled = data.safe_confirmations_enabled;
        
        
        if (data.auto_archive_days !== undefined) updatePayload.auto_archive_days = data.auto_archive_days;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return user_settings;
    }

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

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

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


        return user_settings;
    }

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

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

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

        await user_settings.destroy({
            transaction
        });

        return user_settings;
    }

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

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

        if (!user_settings) {
            return user_settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organizations = await user_settings.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.time_zone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_settings',
                        'time_zone',
                        filter.time_zone,
                    ),
                };
            }
            
            if (filter.locale) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_settings',
                        'locale',
                        filter.locale,
                    ),
                };
            }
            
            if (filter.preferred_voice) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_settings',
                        'preferred_voice',
                        filter.preferred_voice,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.theme) {
                where = {
                    ...where,
                theme: filter.theme,
            };
            }
            
            if (filter.default_entry_mode) {
                where = {
                    ...where,
                default_entry_mode: filter.default_entry_mode,
            };
            }
            
            if (filter.voice_mode_enabled) {
                where = {
                    ...where,
                voice_mode_enabled: filter.voice_mode_enabled,
            };
            }
            
            if (filter.safe_confirmations_enabled) {
                where = {
                    ...where,
                safe_confirmations_enabled: filter.safe_confirmations_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.user_settings.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(
                        'user_settings',
                        'time_zone',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

