
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,
        
        reading_at: data.reading_at
        ||
        null
            ,
            
        metric: data.metric
        ||
        null
            ,
            
        metric_value: data.metric_value
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await machine_readings.setMachine( data.machine || 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,
                
                reading_at: item.reading_at
            ||
            null
            ,
            
                metric: item.metric
            ||
            null
            ,
            
                metric_value: item.metric_value
            ||
            null
            ,
            
                source: item.source
            ||
            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 machine_readings = await db.machine_readings.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.reading_at !== undefined) updatePayload.reading_at = data.reading_at;
        
        
        if (data.metric !== undefined) updatePayload.metric = data.metric;
        
        
        if (data.metric_value !== undefined) updatePayload.metric_value = data.metric_value;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        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 }
            );
        }
        

        
        

        

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

        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.machines,
        as: 'machine',
        
        where: filter.machine ? {
          [Op.or]: [
            { id: { [Op.in]: filter.machine.split('|').map(term => Utils.uuid(term)) } },
            {
              machine_name: {
                [Op.or]: filter.machine.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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


      



            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.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, ) {
        let where = {};
        
        

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

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

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

    
};

