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

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

        const fasting_sessions = await db.fasting_sessions.create(
            {
                id: data.id || undefined,
        
        protocol: data.protocol
        ||
        null
            ,
            
        fast_start: data.fast_start
        ||
        null
            ,
            
        fast_end: data.fast_end
        ||
        null
            ,
            
        eating_window_start: data.eating_window_start
        ||
        null
            ,
            
        eating_window_end: data.eating_window_end
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return fasting_sessions;
    }
    

    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 fasting_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                protocol: item.protocol
            ||
            null
            ,
            
                fast_start: item.fast_start
            ||
            null
            ,
            
                fast_end: item.fast_end
            ||
            null
            ,
            
                eating_window_start: item.eating_window_start
            ||
            null
            ,
            
                eating_window_end: item.eating_window_end
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return fasting_sessions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.protocol !== undefined) updatePayload.protocol = data.protocol;
        
        
        if (data.fast_start !== undefined) updatePayload.fast_start = data.fast_start;
        
        
        if (data.fast_end !== undefined) updatePayload.fast_end = data.fast_end;
        
        
        if (data.eating_window_start !== undefined) updatePayload.eating_window_start = data.eating_window_start;
        
        
        if (data.eating_window_end !== undefined) updatePayload.eating_window_end = data.eating_window_end;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return fasting_sessions;
    }

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

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

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


        return fasting_sessions;
    }

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

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

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

        await fasting_sessions.destroy({
            transaction
        });

        return fasting_sessions;
    }

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

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

        if (!fasting_sessions) {
            return fasting_sessions;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

