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

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

        const routing_operations = await db.routing_operations.create(
            {
                id: data.id || undefined,
        
        operation_sequence: data.operation_sequence
        ||
        null
            ,
            
        operation_name: data.operation_name
        ||
        null
            ,
            
        setup_time_minutes: data.setup_time_minutes
        ||
        null
            ,
            
        run_time_minutes_per_unit: data.run_time_minutes_per_unit
        ||
        null
            ,
            
        queue_time_minutes: data.queue_time_minutes
        ||
        null
            ,
            
        move_time_minutes: data.move_time_minutes
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await routing_operations.setRouting( data.routing || null, {
            transaction,
        });
        
        await routing_operations.setWork_center( data.work_center || null, {
            transaction,
        });
        

        

        

        return routing_operations;
    }
    

    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 routing_operationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                operation_sequence: item.operation_sequence
            ||
            null
            ,
            
                operation_name: item.operation_name
            ||
            null
            ,
            
                setup_time_minutes: item.setup_time_minutes
            ||
            null
            ,
            
                run_time_minutes_per_unit: item.run_time_minutes_per_unit
            ||
            null
            ,
            
                queue_time_minutes: item.queue_time_minutes
            ||
            null
            ,
            
                move_time_minutes: item.move_time_minutes
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return routing_operations;
    }

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

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


        

        const updatePayload = {};
        
        if (data.operation_sequence !== undefined) updatePayload.operation_sequence = data.operation_sequence;
        
        
        if (data.operation_name !== undefined) updatePayload.operation_name = data.operation_name;
        
        
        if (data.setup_time_minutes !== undefined) updatePayload.setup_time_minutes = data.setup_time_minutes;
        
        
        if (data.run_time_minutes_per_unit !== undefined) updatePayload.run_time_minutes_per_unit = data.run_time_minutes_per_unit;
        
        
        if (data.queue_time_minutes !== undefined) updatePayload.queue_time_minutes = data.queue_time_minutes;
        
        
        if (data.move_time_minutes !== undefined) updatePayload.move_time_minutes = data.move_time_minutes;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.routing !== undefined) {
            await routing_operations.setRouting(
              
              data.routing,
              
              { transaction }
            );
        }
        
        if (data.work_center !== undefined) {
            await routing_operations.setWork_center(
              
              data.work_center,
              
              { transaction }
            );
        }
        

        
        

        

        return routing_operations;
    }

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

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

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


        return routing_operations;
    }

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

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

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

        await routing_operations.destroy({
            transaction
        });

        return routing_operations;
    }

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

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

        if (!routing_operations) {
            return routing_operations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.routing = await routing_operations.getRouting({
            transaction
        });
        
        
        output.work_center = await routing_operations.getWork_center({
            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.routings,
        as: 'routing',
        
        where: filter.routing ? {
          [Op.or]: [
            { id: { [Op.in]: filter.routing.split('|').map(term => Utils.uuid(term)) } },
            {
              routing_code: {
                [Op.or]: filter.routing.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.operation_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'routing_operations',
                        'operation_name',
                        filter.operation_name,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'routing_operations',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            


      

      



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

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

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

    
};

