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

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

        const sleep_logs = await db.sleep_logs.create(
            {
                id: data.id || undefined,
        
        bedtime: data.bedtime
        ||
        null
            ,
            
        sleep_onset_time: data.sleep_onset_time
        ||
        null
            ,
            
        awakenings_count: data.awakenings_count
        ||
        null
            ,
            
        final_wake_time: data.final_wake_time
        ||
        null
            ,
            
        out_of_bed_time: data.out_of_bed_time
        ||
        null
            ,
            
        total_sleep_minutes: data.total_sleep_minutes
        ||
        null
            ,
            
        sleep_quality: data.sleep_quality
        ||
        null
            ,
            
        dream_recall: data.dream_recall
        ||
        false
        
            ,
            
        dream_notes: data.dream_notes
        ||
        null
            ,
            
        morning_energy: data.morning_energy
        ||
        null
            ,
            
        sleep_aids_used: data.sleep_aids_used
        ||
        null
            ,
            
        disturbances: data.disturbances
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return sleep_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 sleep_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                bedtime: item.bedtime
            ||
            null
            ,
            
                sleep_onset_time: item.sleep_onset_time
            ||
            null
            ,
            
                awakenings_count: item.awakenings_count
            ||
            null
            ,
            
                final_wake_time: item.final_wake_time
            ||
            null
            ,
            
                out_of_bed_time: item.out_of_bed_time
            ||
            null
            ,
            
                total_sleep_minutes: item.total_sleep_minutes
            ||
            null
            ,
            
                sleep_quality: item.sleep_quality
            ||
            null
            ,
            
                dream_recall: item.dream_recall
            ||
            false
        
            ,
            
                dream_notes: item.dream_notes
            ||
            null
            ,
            
                morning_energy: item.morning_energy
            ||
            null
            ,
            
                sleep_aids_used: item.sleep_aids_used
            ||
            null
            ,
            
                disturbances: item.disturbances
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return sleep_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.bedtime !== undefined) updatePayload.bedtime = data.bedtime;
        
        
        if (data.sleep_onset_time !== undefined) updatePayload.sleep_onset_time = data.sleep_onset_time;
        
        
        if (data.awakenings_count !== undefined) updatePayload.awakenings_count = data.awakenings_count;
        
        
        if (data.final_wake_time !== undefined) updatePayload.final_wake_time = data.final_wake_time;
        
        
        if (data.out_of_bed_time !== undefined) updatePayload.out_of_bed_time = data.out_of_bed_time;
        
        
        if (data.total_sleep_minutes !== undefined) updatePayload.total_sleep_minutes = data.total_sleep_minutes;
        
        
        if (data.sleep_quality !== undefined) updatePayload.sleep_quality = data.sleep_quality;
        
        
        if (data.dream_recall !== undefined) updatePayload.dream_recall = data.dream_recall;
        
        
        if (data.dream_notes !== undefined) updatePayload.dream_notes = data.dream_notes;
        
        
        if (data.morning_energy !== undefined) updatePayload.morning_energy = data.morning_energy;
        
        
        if (data.sleep_aids_used !== undefined) updatePayload.sleep_aids_used = data.sleep_aids_used;
        
        
        if (data.disturbances !== undefined) updatePayload.disturbances = data.disturbances;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return sleep_logs;
    }

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

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

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


        return sleep_logs;
    }

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

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

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

        await sleep_logs.destroy({
            transaction
        });

        return sleep_logs;
    }

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

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

        if (!sleep_logs) {
            return sleep_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await sleep_logs.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.dream_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sleep_logs',
                        'dream_notes',
                        filter.dream_notes,
                    ),
                };
            }
            
            if (filter.sleep_aids_used) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sleep_logs',
                        'sleep_aids_used',
                        filter.sleep_aids_used,
                    ),
                };
            }
            
            if (filter.disturbances) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sleep_logs',
                        'disturbances',
                        filter.disturbances,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.dream_recall) {
                where = {
                    ...where,
                dream_recall: filter.dream_recall,
            };
            }
            


      



            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.sleep_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(
                        'sleep_logs',
                        'disturbances',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

