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

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

        const machine_readings = await db.machine_readings.create(
            {
                id: data.id || undefined,
        
        recorded_at: data.recorded_at
        ||
        null
            ,
            
        run_minutes: data.run_minutes
        ||
        null
            ,
            
        down_minutes: data.down_minutes
        ||
        null
            ,
            
        good_count: data.good_count
        ||
        null
            ,
            
        scrap_count: data.scrap_count
        ||
        null
            ,
            
        cycle_time_seconds: data.cycle_time_seconds
        ||
        null
            ,
            
        energy_kwh: data.energy_kwh
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await machine_readings.setMachine( data.machine || null, {
            transaction,
        });
        
        await machine_readings.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return machine_readings;
    }
    

    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 machine_readingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                recorded_at: item.recorded_at
            ||
            null
            ,
            
                run_minutes: item.run_minutes
            ||
            null
            ,
            
                down_minutes: item.down_minutes
            ||
            null
            ,
            
                good_count: item.good_count
            ||
            null
            ,
            
                scrap_count: item.scrap_count
            ||
            null
            ,
            
                cycle_time_seconds: item.cycle_time_seconds
            ||
            null
            ,
            
                energy_kwh: item.energy_kwh
            ||
            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 machine_readings = await db.machine_readings.bulkCreate(machine_readingsData, { transaction });

        // For each item created, replace relation files
        

        return machine_readings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.recorded_at !== undefined) updatePayload.recorded_at = data.recorded_at;
        
        
        if (data.run_minutes !== undefined) updatePayload.run_minutes = data.run_minutes;
        
        
        if (data.down_minutes !== undefined) updatePayload.down_minutes = data.down_minutes;
        
        
        if (data.good_count !== undefined) updatePayload.good_count = data.good_count;
        
        
        if (data.scrap_count !== undefined) updatePayload.scrap_count = data.scrap_count;
        
        
        if (data.cycle_time_seconds !== undefined) updatePayload.cycle_time_seconds = data.cycle_time_seconds;
        
        
        if (data.energy_kwh !== undefined) updatePayload.energy_kwh = data.energy_kwh;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.machine !== undefined) {
            await machine_readings.setMachine(
              
              data.machine,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await machine_readings.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return machine_readings;
    }

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

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

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


        return machine_readings;
    }

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

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

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

        await machine_readings.destroy({
            transaction
        });

        return machine_readings;
    }

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

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

        if (!machine_readings) {
            return machine_readings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.machine = await machine_readings.getMachine({
            transaction
        });
        
        
        output.organizations = await machine_readings.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.machines,
        as: 'machine',
        
        where: filter.machine ? {
          [Op.or]: [
            { id: { [Op.in]: filter.machine.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.machine.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.machine_readings.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'machine_readings',
                        'notes',
                        query,
                    ),
                ],
            };
        }

        const records = await db.machine_readings.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,
        }));
    }

    
};

