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

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

        const mood_entries = await db.mood_entries.create(
            {
                id: data.id || undefined,
        
        mood: data.mood
        ||
        null
            ,
            
        confidence_level: data.confidence_level
        ||
        null
            ,
            
        discipline_level: data.discipline_level
        ||
        null
            ,
            
        stress_score: data.stress_score
        ||
        null
            ,
            
        emotions_notes: data.emotions_notes
        ||
        null
            ,
            
        recorded_at: data.recorded_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await mood_entries.setTrade( data.trade || null, {
            transaction,
        });
        

        

        

        return mood_entries;
    }
    

    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_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                mood: item.mood
            ||
            null
            ,
            
                confidence_level: item.confidence_level
            ||
            null
            ,
            
                discipline_level: item.discipline_level
            ||
            null
            ,
            
                stress_score: item.stress_score
            ||
            null
            ,
            
                emotions_notes: item.emotions_notes
            ||
            null
            ,
            
                recorded_at: item.recorded_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return mood_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.mood !== undefined) updatePayload.mood = data.mood;
        
        
        if (data.confidence_level !== undefined) updatePayload.confidence_level = data.confidence_level;
        
        
        if (data.discipline_level !== undefined) updatePayload.discipline_level = data.discipline_level;
        
        
        if (data.stress_score !== undefined) updatePayload.stress_score = data.stress_score;
        
        
        if (data.emotions_notes !== undefined) updatePayload.emotions_notes = data.emotions_notes;
        
        
        if (data.recorded_at !== undefined) updatePayload.recorded_at = data.recorded_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trade !== undefined) {
            await mood_entries.setTrade(
              
              data.trade,
              
              { transaction }
            );
        }
        

        
        

        

        return mood_entries;
    }

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

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

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


        return mood_entries;
    }

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

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

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

        await mood_entries.destroy({
            transaction
        });

        return mood_entries;
    }

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

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

        if (!mood_entries) {
            return mood_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.trade = await mood_entries.getTrade({
            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.trades,
        as: 'trade',
        
        where: filter.trade ? {
          [Op.or]: [
            { id: { [Op.in]: filter.trade.split('|').map(term => Utils.uuid(term)) } },
            {
              notes: {
                [Op.or]: filter.trade.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

            
            if (filter.mood) {
                where = {
                    ...where,
                mood: filter.mood,
            };
            }
            
            if (filter.confidence_level) {
                where = {
                    ...where,
                confidence_level: filter.confidence_level,
            };
            }
            
            if (filter.discipline_level) {
                where = {
                    ...where,
                discipline_level: filter.discipline_level,
            };
            }
            


      



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

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

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

    
};

