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

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

        const mood_logs = await db.mood_logs.create(
            {
                id: data.id || undefined,
        
        logged_at: data.logged_at
        ||
        null
            ,
            
        mood_score: data.mood_score
        ||
        null
            ,
            
        emotion_tags_csv: data.emotion_tags_csv
        ||
        null
            ,
            
        energy_level: data.energy_level
        ||
        null
            ,
            
        anxiety_level: data.anxiety_level
        ||
        null
            ,
            
        contributing_factors: data.contributing_factors
        ||
        null
            ,
            
        journal_entry: data.journal_entry
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

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

        return mood_logs;
    }
    

    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 mood_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                logged_at: item.logged_at
            ||
            null
            ,
            
                mood_score: item.mood_score
            ||
            null
            ,
            
                emotion_tags_csv: item.emotion_tags_csv
            ||
            null
            ,
            
                energy_level: item.energy_level
            ||
            null
            ,
            
                anxiety_level: item.anxiety_level
            ||
            null
            ,
            
                contributing_factors: item.contributing_factors
            ||
            null
            ,
            
                journal_entry: item.journal_entry
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return mood_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.logged_at !== undefined) updatePayload.logged_at = data.logged_at;
        
        
        if (data.mood_score !== undefined) updatePayload.mood_score = data.mood_score;
        
        
        if (data.emotion_tags_csv !== undefined) updatePayload.emotion_tags_csv = data.emotion_tags_csv;
        
        
        if (data.energy_level !== undefined) updatePayload.energy_level = data.energy_level;
        
        
        if (data.anxiety_level !== undefined) updatePayload.anxiety_level = data.anxiety_level;
        
        
        if (data.contributing_factors !== undefined) updatePayload.contributing_factors = data.contributing_factors;
        
        
        if (data.journal_entry !== undefined) updatePayload.journal_entry = data.journal_entry;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return mood_logs;
    }

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

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

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


        return mood_logs;
    }

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

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

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

        await mood_logs.destroy({
            transaction
        });

        return mood_logs;
    }

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

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

        if (!mood_logs) {
            return mood_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await mood_logs.getUser({
            transaction
        });
        
        
        output.moment_photo = await mood_logs.getMoment_photo({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.emotion_tags_csv) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mood_logs',
                        'emotion_tags_csv',
                        filter.emotion_tags_csv,
                    ),
                };
            }
            
            if (filter.contributing_factors) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mood_logs',
                        'contributing_factors',
                        filter.contributing_factors,
                    ),
                };
            }
            
            if (filter.journal_entry) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mood_logs',
                        'journal_entry',
                        filter.journal_entry,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            logged_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    logged_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

            


      



            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.mood_logs.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(
                        'mood_logs',
                        'contributing_factors',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

