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

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

        const app_settings = await db.app_settings.create(
            {
                id: data.id || undefined,
        
        theme_mode: data.theme_mode
        ||
        null
            ,
            
        font_size: data.font_size
        ||
        null
            ,
            
        high_contrast_mode: data.high_contrast_mode
        ||
        false
        
            ,
            
        reduce_motion: data.reduce_motion
        ||
        false
        
            ,
            
        color_blind_mode: data.color_blind_mode
        ||
        false
        
            ,
            
        voice_input_enabled: data.voice_input_enabled
        ||
        false
        
            ,
            
        auto_lock_minutes: data.auto_lock_minutes
        ||
        null
            ,
            
        biometric_lock_enabled: data.biometric_lock_enabled
        ||
        false
        
            ,
            
        incognito_mode_enabled: data.incognito_mode_enabled
        ||
        false
        
            ,
            
        anthropic_api_key_encrypted: data.anthropic_api_key_encrypted
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await app_settings.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return app_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 app_settingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                theme_mode: item.theme_mode
            ||
            null
            ,
            
                font_size: item.font_size
            ||
            null
            ,
            
                high_contrast_mode: item.high_contrast_mode
            ||
            false
        
            ,
            
                reduce_motion: item.reduce_motion
            ||
            false
        
            ,
            
                color_blind_mode: item.color_blind_mode
            ||
            false
        
            ,
            
                voice_input_enabled: item.voice_input_enabled
            ||
            false
        
            ,
            
                auto_lock_minutes: item.auto_lock_minutes
            ||
            null
            ,
            
                biometric_lock_enabled: item.biometric_lock_enabled
            ||
            false
        
            ,
            
                incognito_mode_enabled: item.incognito_mode_enabled
            ||
            false
        
            ,
            
                anthropic_api_key_encrypted: item.anthropic_api_key_encrypted
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return app_settings;
    }

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

        const app_settings = await db.app_settings.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.theme_mode !== undefined) updatePayload.theme_mode = data.theme_mode;
        
        
        if (data.font_size !== undefined) updatePayload.font_size = data.font_size;
        
        
        if (data.high_contrast_mode !== undefined) updatePayload.high_contrast_mode = data.high_contrast_mode;
        
        
        if (data.reduce_motion !== undefined) updatePayload.reduce_motion = data.reduce_motion;
        
        
        if (data.color_blind_mode !== undefined) updatePayload.color_blind_mode = data.color_blind_mode;
        
        
        if (data.voice_input_enabled !== undefined) updatePayload.voice_input_enabled = data.voice_input_enabled;
        
        
        if (data.auto_lock_minutes !== undefined) updatePayload.auto_lock_minutes = data.auto_lock_minutes;
        
        
        if (data.biometric_lock_enabled !== undefined) updatePayload.biometric_lock_enabled = data.biometric_lock_enabled;
        
        
        if (data.incognito_mode_enabled !== undefined) updatePayload.incognito_mode_enabled = data.incognito_mode_enabled;
        
        
        if (data.anthropic_api_key_encrypted !== undefined) updatePayload.anthropic_api_key_encrypted = data.anthropic_api_key_encrypted;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return app_settings;
    }

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

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

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


        return app_settings;
    }

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

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

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

        await app_settings.destroy({
            transaction
        });

        return app_settings;
    }

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

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

        if (!app_settings) {
            return app_settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await app_settings.getUser({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.anthropic_api_key_encrypted) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'app_settings',
                        'anthropic_api_key_encrypted',
                        filter.anthropic_api_key_encrypted,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.theme_mode) {
                where = {
                    ...where,
                theme_mode: filter.theme_mode,
            };
            }
            
            if (filter.font_size) {
                where = {
                    ...where,
                font_size: filter.font_size,
            };
            }
            
            if (filter.high_contrast_mode) {
                where = {
                    ...where,
                high_contrast_mode: filter.high_contrast_mode,
            };
            }
            
            if (filter.reduce_motion) {
                where = {
                    ...where,
                reduce_motion: filter.reduce_motion,
            };
            }
            
            if (filter.color_blind_mode) {
                where = {
                    ...where,
                color_blind_mode: filter.color_blind_mode,
            };
            }
            
            if (filter.voice_input_enabled) {
                where = {
                    ...where,
                voice_input_enabled: filter.voice_input_enabled,
            };
            }
            
            if (filter.biometric_lock_enabled) {
                where = {
                    ...where,
                biometric_lock_enabled: filter.biometric_lock_enabled,
            };
            }
            
            if (filter.incognito_mode_enabled) {
                where = {
                    ...where,
                incognito_mode_enabled: filter.incognito_mode_enabled,
            };
            }
            


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.app_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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'app_settings',
                        'anthropic_api_key_encrypted',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

