
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,
        
        downtime_type: data.downtime_type
        ||
        null
            ,
            
        reason_category: data.reason_category
        ||
        null
            ,
            
        reason_detail: data.reason_detail
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        duration_minutes: data.duration_minutes
        ||
        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.setReported_by_user( data.reported_by_user || null, {
            transaction,
        });
        
        await machine_downtime_events.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        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,
                
                downtime_type: item.downtime_type
            ||
            null
            ,
            
                reason_category: item.reason_category
            ||
            null
            ,
            
                reason_detail: item.reason_detail
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                duration_minutes: item.duration_minutes
            ||
            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
        

        return machine_downtime_events;
    }

    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_downtime_events = await db.machine_downtime_events.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.downtime_type !== undefined) updatePayload.downtime_type = data.downtime_type;
        
        
        if (data.reason_category !== undefined) updatePayload.reason_category = data.reason_category;
        
        
        if (data.reason_detail !== undefined) updatePayload.reason_detail = data.reason_detail;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.duration_minutes !== undefined) updatePayload.duration_minutes = data.duration_minutes;
        
        
        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.reported_by_user !== undefined) {
            await machine_downtime_events.setReported_by_user(
              
              data.reported_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await machine_downtime_events.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        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.reported_by_user = await machine_downtime_events.getReported_by_user({
            transaction
        });
        
        
        output.organizations = await machine_downtime_events.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.users,
        as: 'reported_by_user',
        
        where: filter.reported_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.reported_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.reported_by_user.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.reason_detail) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'machine_downtime_events',
                        'reason_detail',
                        filter.reason_detail,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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


      

      

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

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

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

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

    
};

