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

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

        const operations = await db.operations.create(
            {
                id: data.id || undefined,
        
        operation_name: data.operation_name
        ||
        null
            ,
            
        operation_code: data.operation_code
        ||
        null
            ,
            
        sequence: data.sequence
        ||
        null
            ,
            
        setup_time_minutes: data.setup_time_minutes
        ||
        null
            ,
            
        run_time_minutes_per_unit: data.run_time_minutes_per_unit
        ||
        null
            ,
            
        labor_time_minutes_per_unit: data.labor_time_minutes_per_unit
        ||
        null
            ,
            
        work_instructions: data.work_instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await operations.setRoute( data.route || null, {
            transaction,
        });
        

        

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

        return 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 operationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                operation_name: item.operation_name
            ||
            null
            ,
            
                operation_code: item.operation_code
            ||
            null
            ,
            
                sequence: item.sequence
            ||
            null
            ,
            
                setup_time_minutes: item.setup_time_minutes
            ||
            null
            ,
            
                run_time_minutes_per_unit: item.run_time_minutes_per_unit
            ||
            null
            ,
            
                labor_time_minutes_per_unit: item.labor_time_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 operations = await db.operations.bulkCreate(operationsData, { transaction });

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

        return operations;
    }

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

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


        

        const updatePayload = {};
        
        if (data.operation_name !== undefined) updatePayload.operation_name = data.operation_name;
        
        
        if (data.operation_code !== undefined) updatePayload.operation_code = data.operation_code;
        
        
        if (data.sequence !== undefined) updatePayload.sequence = data.sequence;
        
        
        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.labor_time_minutes_per_unit !== undefined) updatePayload.labor_time_minutes_per_unit = data.labor_time_minutes_per_unit;
        
        
        if (data.work_instructions !== undefined) updatePayload.work_instructions = data.work_instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.route !== undefined) {
            await operations.setRoute(
              
              data.route,
              
              { transaction }
            );
        }
        

        
        

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

        return operations;
    }

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

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

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


        return operations;
    }

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

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

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

        await operations.destroy({
            transaction
        });

        return operations;
    }

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

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

        if (!operations) {
            return operations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.work_order_operations_operation = await operations.getWork_order_operations_operation({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.qa_inspections_operation = await operations.getQa_inspections_operation({
            transaction
        });
        
        
        
        
        
        
        output.route = await operations.getRoute({
            transaction
        });
        
        
        output.instruction_attachments = await operations.getInstruction_attachments({
            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.routes,
        as: 'route',
        
        where: filter.route ? {
          [Op.or]: [
            { id: { [Op.in]: filter.route.split('|').map(term => Utils.uuid(term)) } },
            {
              route_name: {
                [Op.or]: filter.route.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

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

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    labor_time_minutes_per_unit: {
                    ...where.labor_time_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.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(
                        'operations',
                        'operation_name',
                        query,
                    ),
                ],
            };
        }

        const records = await db.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,
        }));
    }

    
};

