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

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

        const downtime_events = await db.downtime_events.create(
            {
                id: data.id || undefined,
        
        event_number: data.event_number
        ||
        null
            ,
            
        reason_category: data.reason_category
        ||
        null
            ,
            
        reason_detail: data.reason_detail
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        planned: data.planned
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await downtime_events.setMachine( data.machine || null, {
            transaction,
        });
        
        await downtime_events.setProduction_operation( data.production_operation || null, {
            transaction,
        });
        
        await downtime_events.setReported_by( data.reported_by || null, {
            transaction,
        });
        
        await downtime_events.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return 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 downtime_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                event_number: item.event_number
            ||
            null
            ,
            
                reason_category: item.reason_category
            ||
            null
            ,
            
                reason_detail: item.reason_detail
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                planned: item.planned
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.event_number !== undefined) updatePayload.event_number = data.event_number;
        
        
        if (data.reason_category !== undefined) updatePayload.reason_category = data.reason_category;
        
        
        if (data.reason_detail !== undefined) updatePayload.reason_detail = data.reason_detail;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.planned !== undefined) updatePayload.planned = data.planned;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.machine !== undefined) {
            await downtime_events.setMachine(
              
              data.machine,
              
              { transaction }
            );
        }
        
        if (data.production_operation !== undefined) {
            await downtime_events.setProduction_operation(
              
              data.production_operation,
              
              { transaction }
            );
        }
        
        if (data.reported_by !== undefined) {
            await downtime_events.setReported_by(
              
              data.reported_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await downtime_events.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return downtime_events;
    }

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

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

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


        return downtime_events;
    }

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

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

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

        await downtime_events.destroy({
            transaction
        });

        return downtime_events;
    }

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

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

        if (!downtime_events) {
            return downtime_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.machine = await downtime_events.getMachine({
            transaction
        });
        
        
        output.production_operation = await downtime_events.getProduction_operation({
            transaction
        });
        
        
        output.reported_by = await downtime_events.getReported_by({
            transaction
        });
        
        
        output.organizations = await 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.production_operations,
        as: 'production_operation',
        
        where: filter.production_operation ? {
          [Op.or]: [
            { id: { [Op.in]: filter.production_operation.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.production_operation.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.event_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'downtime_events',
                        'event_number',
                        filter.event_number,
                    ),
                };
            }
            
            if (filter.reason_detail) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'downtime_events',
                        'reason_detail',
                        filter.reason_detail,
                    ),
                };
            }
            

            
            
            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.reason_category) {
                where = {
                    ...where,
                reason_category: filter.reason_category,
            };
            }
            
            if (filter.planned) {
                where = {
                    ...where,
                planned: filter.planned,
            };
            }
            


      

      

      

      
      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.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(
                        'downtime_events',
                        'event_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

