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

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

        const routing_steps = await db.routing_steps.create(
            {
                id: data.id || undefined,
        
        sequence_number: data.sequence_number
        ||
        null
            ,
            
        step_name: data.step_name
        ||
        null
            ,
            
        setup_time_minutes: data.setup_time_minutes
        ||
        null
            ,
            
        run_time_minutes: data.run_time_minutes
        ||
        null
            ,
            
        work_instructions: data.work_instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

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

        return routing_steps;
    }
    

    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_stepsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sequence_number: item.sequence_number
            ||
            null
            ,
            
                step_name: item.step_name
            ||
            null
            ,
            
                setup_time_minutes: item.setup_time_minutes
            ||
            null
            ,
            
                run_time_minutes: item.run_time_minutes
            ||
            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_steps = await db.routing_steps.bulkCreate(routing_stepsData, { transaction });

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

        return routing_steps;
    }

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

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


        

        const updatePayload = {};
        
        if (data.sequence_number !== undefined) updatePayload.sequence_number = data.sequence_number;
        
        
        if (data.step_name !== undefined) updatePayload.step_name = data.step_name;
        
        
        if (data.setup_time_minutes !== undefined) updatePayload.setup_time_minutes = data.setup_time_minutes;
        
        
        if (data.run_time_minutes !== undefined) updatePayload.run_time_minutes = data.run_time_minutes;
        
        
        if (data.work_instructions !== undefined) updatePayload.work_instructions = data.work_instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return routing_steps;
    }

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

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

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


        return routing_steps;
    }

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

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

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

        await routing_steps.destroy({
            transaction
        });

        return routing_steps;
    }

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

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

        if (!routing_steps) {
            return routing_steps;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.routing = await routing_steps.getRouting({
            transaction
        });
        
        
        output.work_center = await routing_steps.getWork_center({
            transaction
        });
        
        
        output.attachments = await routing_steps.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_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}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.step_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'routing_steps',
                        'step_name',
                        filter.step_name,
                    ),
                };
            }
            
            if (filter.work_instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'routing_steps',
                        'work_instructions',
                        filter.work_instructions,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    sequence_number: {
                    ...where.sequence_number,
                            [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_minutesRange) {
                const [start, end] = filter.run_time_minutesRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    run_time_minutes: {
                    ...where.run_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_steps.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_steps',
                        'step_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

