
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,
        
        push_new_match: data.push_new_match
        ||
        false
        
            ,
            
        push_new_message: data.push_new_message
        ||
        false
        
            ,
            
        push_profile_like: data.push_profile_like
        ||
        false
        
            ,
            
        push_daily_spark: data.push_daily_spark
        ||
        false
        
            ,
            
        push_premium: data.push_premium
        ||
        false
        
            ,
            
        privacy_show_distance: data.privacy_show_distance
        ||
        false
        
            ,
            
        privacy_show_online_status: data.privacy_show_online_status
        ||
        false
        
            ,
            
        privacy_allow_discovery: data.privacy_allow_discovery
        ||
        false
        
            ,
            
        updated_on: data.updated_on
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await user_settings.setUser( data.user || 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,
                
                push_new_match: item.push_new_match
            ||
            false
        
            ,
            
                push_new_message: item.push_new_message
            ||
            false
        
            ,
            
                push_profile_like: item.push_profile_like
            ||
            false
        
            ,
            
                push_daily_spark: item.push_daily_spark
            ||
            false
        
            ,
            
                push_premium: item.push_premium
            ||
            false
        
            ,
            
                privacy_show_distance: item.privacy_show_distance
            ||
            false
        
            ,
            
                privacy_show_online_status: item.privacy_show_online_status
            ||
            false
        
            ,
            
                privacy_allow_discovery: item.privacy_allow_discovery
            ||
            false
        
            ,
            
                updated_on: item.updated_on
            ||
            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 user_settings = await db.user_settings.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.push_new_match !== undefined) updatePayload.push_new_match = data.push_new_match;
        
        
        if (data.push_new_message !== undefined) updatePayload.push_new_message = data.push_new_message;
        
        
        if (data.push_profile_like !== undefined) updatePayload.push_profile_like = data.push_profile_like;
        
        
        if (data.push_daily_spark !== undefined) updatePayload.push_daily_spark = data.push_daily_spark;
        
        
        if (data.push_premium !== undefined) updatePayload.push_premium = data.push_premium;
        
        
        if (data.privacy_show_distance !== undefined) updatePayload.privacy_show_distance = data.privacy_show_distance;
        
        
        if (data.privacy_show_online_status !== undefined) updatePayload.privacy_show_online_status = data.privacy_show_online_status;
        
        
        if (data.privacy_allow_discovery !== undefined) updatePayload.privacy_allow_discovery = data.privacy_allow_discovery;
        
        
        if (data.updated_on !== undefined) updatePayload.updated_on = data.updated_on;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await user_settings.setUser(
              
              data.user,
              
              { 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.user = await user_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.updated_onRange) {
                const [start, end] = filter.updated_onRange;

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

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

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

            
            if (filter.push_new_match) {
                where = {
                    ...where,
                push_new_match: filter.push_new_match,
            };
            }
            
            if (filter.push_new_message) {
                where = {
                    ...where,
                push_new_message: filter.push_new_message,
            };
            }
            
            if (filter.push_profile_like) {
                where = {
                    ...where,
                push_profile_like: filter.push_profile_like,
            };
            }
            
            if (filter.push_daily_spark) {
                where = {
                    ...where,
                push_daily_spark: filter.push_daily_spark,
            };
            }
            
            if (filter.push_premium) {
                where = {
                    ...where,
                push_premium: filter.push_premium,
            };
            }
            
            if (filter.privacy_show_distance) {
                where = {
                    ...where,
                privacy_show_distance: filter.privacy_show_distance,
            };
            }
            
            if (filter.privacy_show_online_status) {
                where = {
                    ...where,
                privacy_show_online_status: filter.privacy_show_online_status,
            };
            }
            
            if (filter.privacy_allow_discovery) {
                where = {
                    ...where,
                privacy_allow_discovery: filter.privacy_allow_discovery,
            };
            }
            


      



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

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

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

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

    
};

