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

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

        const ergonomics_logs = await db.ergonomics_logs.create(
            {
                id: data.id || undefined,
        
        logged_at: data.logged_at
        ||
        null
            ,
            
        sitting_minutes: data.sitting_minutes
        ||
        null
            ,
            
        standing_minutes: data.standing_minutes
        ||
        null
            ,
            
        moving_minutes: data.moving_minutes
        ||
        null
            ,
            
        workstation_notes: data.workstation_notes
        ||
        null
            ,
            
        posture_notes: data.posture_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return ergonomics_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 ergonomics_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                logged_at: item.logged_at
            ||
            null
            ,
            
                sitting_minutes: item.sitting_minutes
            ||
            null
            ,
            
                standing_minutes: item.standing_minutes
            ||
            null
            ,
            
                moving_minutes: item.moving_minutes
            ||
            null
            ,
            
                workstation_notes: item.workstation_notes
            ||
            null
            ,
            
                posture_notes: item.posture_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ergonomics_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.logged_at !== undefined) updatePayload.logged_at = data.logged_at;
        
        
        if (data.sitting_minutes !== undefined) updatePayload.sitting_minutes = data.sitting_minutes;
        
        
        if (data.standing_minutes !== undefined) updatePayload.standing_minutes = data.standing_minutes;
        
        
        if (data.moving_minutes !== undefined) updatePayload.moving_minutes = data.moving_minutes;
        
        
        if (data.workstation_notes !== undefined) updatePayload.workstation_notes = data.workstation_notes;
        
        
        if (data.posture_notes !== undefined) updatePayload.posture_notes = data.posture_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return ergonomics_logs;
    }

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

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

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


        return ergonomics_logs;
    }

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

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

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

        await ergonomics_logs.destroy({
            transaction
        });

        return ergonomics_logs;
    }

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

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

        if (!ergonomics_logs) {
            return ergonomics_logs;
        }

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

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

            
            
            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.sitting_minutesRange) {
                const [start, end] = filter.sitting_minutesRange;

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    moving_minutes: {
                    ...where.moving_minutes,
                            [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.ergonomics_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(
                        'ergonomics_logs',
                        'workstation_notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

