
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_no: data.operation_no
        ||
        null
            ,
            
        operation_name: data.operation_name
        ||
        null
            ,
            
        setup_minutes: data.setup_minutes
        ||
        null
            ,
            
        run_minutes_per_unit: data.run_minutes_per_unit
        ||
        null
            ,
            
        work_instructions: data.work_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,
        });
        

        

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

        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_no: item.operation_no
            ||
            null
            ,
            
                operation_name: item.operation_name
            ||
            null
            ,
            
                setup_minutes: item.setup_minutes
            ||
            null
            ,
            
                run_minutes_per_unit: item.run_minutes_per_unit
            ||
            null
            ,
            
                work_instructions: item.work_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
        
        for (let i = 0; i < routing_operations.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.routing_operations.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: routing_operations[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        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_no !== undefined) updatePayload.operation_no = data.operation_no;
        
        
        if (data.operation_name !== undefined) updatePayload.operation_name = data.operation_name;
        
        
        if (data.setup_minutes !== undefined) updatePayload.setup_minutes = data.setup_minutes;
        
        
        if (data.run_minutes_per_unit !== undefined) updatePayload.run_minutes_per_unit = data.run_minutes_per_unit;
        
        
        if (data.work_instructions !== undefined) updatePayload.work_instructions = data.work_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 }
            );
        }
        

        
        

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

        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
        });
        
        
        output.attachments = await routing_operations.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.routings,
        as: 'routing',
        
        where: filter.routing ? {
          [Op.or]: [
            { id: { [Op.in]: filter.routing.split('|').map(term => Utils.uuid(term)) } },
            {
              routing_name: {
                [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)) } },
            {
              work_center_name: {
                [Op.or]: filter.work_center.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.operation_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'routing_operations',
                        'operation_name',
                        filter.operation_name,
                    ),
                };
            }
            
            if (filter.work_instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'routing_operations',
                        'work_instructions',
                        filter.work_instructions,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    run_minutes_per_unit: {
                    ...where.run_minutes_per_unit,
                            [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,
        }));
    }

    
};

