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

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

        const user_lifestyle_baselines = await db.user_lifestyle_baselines.create(
            {
                id: data.id || undefined,
        
        typical_bedtime: data.typical_bedtime
        ||
        null
            ,
            
        typical_wake_time: data.typical_wake_time
        ||
        null
            ,
            
        alcohol_use: data.alcohol_use
        ||
        null
            ,
            
        tobacco_nicotine_use: data.tobacco_nicotine_use
        ||
        null
            ,
            
        recreational_substance_use: data.recreational_substance_use
        ||
        null
            ,
            
        caffeine_servings_per_day: data.caffeine_servings_per_day
        ||
        null
            ,
            
        typical_stress_level: data.typical_stress_level
        ||
        null
            ,
            
        occupation_type: data.occupation_type
        ||
        null
            ,
            
        avg_daily_steps_estimate: data.avg_daily_steps_estimate
        ||
        null
            ,
            
        currently_exercises: data.currently_exercises
        ||
        false
        
            ,
            
        exercise_types: data.exercise_types
        ||
        null
            ,
            
        diet_pattern: data.diet_pattern
        ||
        null
            ,
            
        diet_pattern_other: data.diet_pattern_other
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return user_lifestyle_baselines;
    }
    

    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_lifestyle_baselinesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                typical_bedtime: item.typical_bedtime
            ||
            null
            ,
            
                typical_wake_time: item.typical_wake_time
            ||
            null
            ,
            
                alcohol_use: item.alcohol_use
            ||
            null
            ,
            
                tobacco_nicotine_use: item.tobacco_nicotine_use
            ||
            null
            ,
            
                recreational_substance_use: item.recreational_substance_use
            ||
            null
            ,
            
                caffeine_servings_per_day: item.caffeine_servings_per_day
            ||
            null
            ,
            
                typical_stress_level: item.typical_stress_level
            ||
            null
            ,
            
                occupation_type: item.occupation_type
            ||
            null
            ,
            
                avg_daily_steps_estimate: item.avg_daily_steps_estimate
            ||
            null
            ,
            
                currently_exercises: item.currently_exercises
            ||
            false
        
            ,
            
                exercise_types: item.exercise_types
            ||
            null
            ,
            
                diet_pattern: item.diet_pattern
            ||
            null
            ,
            
                diet_pattern_other: item.diet_pattern_other
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return user_lifestyle_baselines;
    }

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

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


        

        const updatePayload = {};
        
        if (data.typical_bedtime !== undefined) updatePayload.typical_bedtime = data.typical_bedtime;
        
        
        if (data.typical_wake_time !== undefined) updatePayload.typical_wake_time = data.typical_wake_time;
        
        
        if (data.alcohol_use !== undefined) updatePayload.alcohol_use = data.alcohol_use;
        
        
        if (data.tobacco_nicotine_use !== undefined) updatePayload.tobacco_nicotine_use = data.tobacco_nicotine_use;
        
        
        if (data.recreational_substance_use !== undefined) updatePayload.recreational_substance_use = data.recreational_substance_use;
        
        
        if (data.caffeine_servings_per_day !== undefined) updatePayload.caffeine_servings_per_day = data.caffeine_servings_per_day;
        
        
        if (data.typical_stress_level !== undefined) updatePayload.typical_stress_level = data.typical_stress_level;
        
        
        if (data.occupation_type !== undefined) updatePayload.occupation_type = data.occupation_type;
        
        
        if (data.avg_daily_steps_estimate !== undefined) updatePayload.avg_daily_steps_estimate = data.avg_daily_steps_estimate;
        
        
        if (data.currently_exercises !== undefined) updatePayload.currently_exercises = data.currently_exercises;
        
        
        if (data.exercise_types !== undefined) updatePayload.exercise_types = data.exercise_types;
        
        
        if (data.diet_pattern !== undefined) updatePayload.diet_pattern = data.diet_pattern;
        
        
        if (data.diet_pattern_other !== undefined) updatePayload.diet_pattern_other = data.diet_pattern_other;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return user_lifestyle_baselines;
    }

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

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

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


        return user_lifestyle_baselines;
    }

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

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

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

        await user_lifestyle_baselines.destroy({
            transaction
        });

        return user_lifestyle_baselines;
    }

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

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

        if (!user_lifestyle_baselines) {
            return user_lifestyle_baselines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await user_lifestyle_baselines.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.typical_bedtime) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_lifestyle_baselines',
                        'typical_bedtime',
                        filter.typical_bedtime,
                    ),
                };
            }
            
            if (filter.typical_wake_time) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_lifestyle_baselines',
                        'typical_wake_time',
                        filter.typical_wake_time,
                    ),
                };
            }
            
            if (filter.recreational_substance_use) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_lifestyle_baselines',
                        'recreational_substance_use',
                        filter.recreational_substance_use,
                    ),
                };
            }
            
            if (filter.exercise_types) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_lifestyle_baselines',
                        'exercise_types',
                        filter.exercise_types,
                    ),
                };
            }
            
            if (filter.diet_pattern_other) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_lifestyle_baselines',
                        'diet_pattern_other',
                        filter.diet_pattern_other,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.alcohol_use) {
                where = {
                    ...where,
                alcohol_use: filter.alcohol_use,
            };
            }
            
            if (filter.tobacco_nicotine_use) {
                where = {
                    ...where,
                tobacco_nicotine_use: filter.tobacco_nicotine_use,
            };
            }
            
            if (filter.occupation_type) {
                where = {
                    ...where,
                occupation_type: filter.occupation_type,
            };
            }
            
            if (filter.currently_exercises) {
                where = {
                    ...where,
                currently_exercises: filter.currently_exercises,
            };
            }
            
            if (filter.diet_pattern) {
                where = {
                    ...where,
                diet_pattern: filter.diet_pattern,
            };
            }
            


      



            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_lifestyle_baselines.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_lifestyle_baselines',
                        'diet_pattern_other',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

