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

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

        const production_operations = await db.production_operations.create(
            {
                id: data.id || undefined,
        
        operation_number: data.operation_number
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        planned_start: data.planned_start
        ||
        null
            ,
            
        planned_end: data.planned_end
        ||
        null
            ,
            
        actual_start: data.actual_start
        ||
        null
            ,
            
        actual_end: data.actual_end
        ||
        null
            ,
            
        good_qty: data.good_qty
        ||
        null
            ,
            
        scrap_qty: data.scrap_qty
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await production_operations.setProduction_order( data.production_order || null, {
            transaction,
        });
        
        await production_operations.setRouting_step( data.routing_step || null, {
            transaction,
        });
        
        await production_operations.setWork_center( data.work_center || null, {
            transaction,
        });
        
        await production_operations.setMachine( data.machine || null, {
            transaction,
        });
        
        await production_operations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return production_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 production_operationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                operation_number: item.operation_number
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                planned_start: item.planned_start
            ||
            null
            ,
            
                planned_end: item.planned_end
            ||
            null
            ,
            
                actual_start: item.actual_start
            ||
            null
            ,
            
                actual_end: item.actual_end
            ||
            null
            ,
            
                good_qty: item.good_qty
            ||
            null
            ,
            
                scrap_qty: item.scrap_qty
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return production_operations;
    }

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


        

        const updatePayload = {};
        
        if (data.operation_number !== undefined) updatePayload.operation_number = data.operation_number;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.planned_start !== undefined) updatePayload.planned_start = data.planned_start;
        
        
        if (data.planned_end !== undefined) updatePayload.planned_end = data.planned_end;
        
        
        if (data.actual_start !== undefined) updatePayload.actual_start = data.actual_start;
        
        
        if (data.actual_end !== undefined) updatePayload.actual_end = data.actual_end;
        
        
        if (data.good_qty !== undefined) updatePayload.good_qty = data.good_qty;
        
        
        if (data.scrap_qty !== undefined) updatePayload.scrap_qty = data.scrap_qty;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.production_order !== undefined) {
            await production_operations.setProduction_order(
              
              data.production_order,
              
              { transaction }
            );
        }
        
        if (data.routing_step !== undefined) {
            await production_operations.setRouting_step(
              
              data.routing_step,
              
              { transaction }
            );
        }
        
        if (data.work_center !== undefined) {
            await production_operations.setWork_center(
              
              data.work_center,
              
              { transaction }
            );
        }
        
        if (data.machine !== undefined) {
            await production_operations.setMachine(
              
              data.machine,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await production_operations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return production_operations;
    }

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

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

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


        return production_operations;
    }

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

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

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

        await production_operations.destroy({
            transaction
        });

        return production_operations;
    }

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

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

        if (!production_operations) {
            return production_operations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.downtime_events_production_operation = await production_operations.getDowntime_events_production_operation({
            transaction
        });
        
        
        
        
        
        
        
        
        output.production_order = await production_operations.getProduction_order({
            transaction
        });
        
        
        output.routing_step = await production_operations.getRouting_step({
            transaction
        });
        
        
        output.work_center = await production_operations.getWork_center({
            transaction
        });
        
        
        output.machine = await production_operations.getMachine({
            transaction
        });
        
        
        output.organizations = await production_operations.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.production_orders,
        as: 'production_order',
        
        where: filter.production_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.production_order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_number: {
                [Op.or]: filter.production_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.routing_steps,
        as: 'routing_step',
        
        where: filter.routing_step ? {
          [Op.or]: [
            { id: { [Op.in]: filter.routing_step.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.routing_step.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.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_operations',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_operations',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      

      

      

      
      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.production_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'production_operations',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

