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

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

        const machine_downtime_events = await db.machine_downtime_events.create(
            {
                id: data.id || undefined,
        
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        downtime_category: data.downtime_category
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await machine_downtime_events.setMachine( data.machine || null, {
            transaction,
        });
        
        await machine_downtime_events.setWork_order( data.work_order || null, {
            transaction,
        });
        
        await machine_downtime_events.setReported_by( data.reported_by || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.machine_downtime_events.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: machine_downtime_events.id,
            },
            data.attachments,
            options,
        );
        

        return machine_downtime_events;
    }
    

    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_downtime_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                downtime_category: item.downtime_category
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < machine_downtime_events.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.machine_downtime_events.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: machine_downtime_events[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return machine_downtime_events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.downtime_category !== undefined) updatePayload.downtime_category = data.downtime_category;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.machine !== undefined) {
            await machine_downtime_events.setMachine(
              
              data.machine,
              
              { transaction }
            );
        }
        
        if (data.work_order !== undefined) {
            await machine_downtime_events.setWork_order(
              
              data.work_order,
              
              { transaction }
            );
        }
        
        if (data.reported_by !== undefined) {
            await machine_downtime_events.setReported_by(
              
              data.reported_by,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.machine_downtime_events.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: machine_downtime_events.id,
            },
            data.attachments,
            options,
        );
        

        return machine_downtime_events;
    }

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

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

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


        return machine_downtime_events;
    }

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

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

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

        await machine_downtime_events.destroy({
            transaction
        });

        return machine_downtime_events;
    }

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

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

        if (!machine_downtime_events) {
            return machine_downtime_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.machine = await machine_downtime_events.getMachine({
            transaction
        });
        
        
        output.work_order = await machine_downtime_events.getWork_order({
            transaction
        });
        
        
        output.reported_by = await machine_downtime_events.getReported_by({
            transaction
        });
        
        
        output.attachments = await machine_downtime_events.getAttachments({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

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

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

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

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

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

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

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

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

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


      

      

      



            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_downtime_events.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_downtime_events',
                        'reason',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

