our code
app.js
const express = require('express');
const bcrypt = require('bcrypt');
const mysql = require('mysql2/promise');

const app = express();
app.use(express.json());
// MySQL database connection
const db = mysql.createPool({
    host: 'localhost',
    user: 'jaleel',
    password: 'Zeeshan@7867',
    database: 'jaleel',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// Check database connection status
db.getConnection()
    .then(connection => {
        console.log('Database connection successful!');
        connection.release(); // Release the connection
    })
    .catch(error => {
        console.error('Error connecting to database:', error);
    });

// Middleware to validate API key
const validateApiKey = async (req, res, next) => {
    const apiKey = req.headers['api-key'];

    if (!apiKey) {
        return res.status(401).json({ message: "API key is required." });
    }

    try {
        const [user] = await db.query('SELECT * FROM Users WHERE APIKey = ?', [apiKey]);

        if (!user) {
            return res.status(401).json({ message: "Invalid API key." });
        }

        req.user = user;
        next();
    } catch (error) {
        console.error("Error:", error.message);
        res.status(500).json({ message: "Internal Server Error" });
    }
};

// Scan SKU endpoint
app.post('/api/scan', validateApiKey, async (req, res) => {
    const { sku } = req.body;

    if (!sku) {
        return res.status(400).json({ message: "SKU is required." });
    }

    try {
        // Fetch product details by SKU
        const [product] = await db.query('SELECT * FROM Products WHERE SKU = ?', [sku]);

        if (!product) {
            return res.status(404).json({ message: "Product not found." });
        }

        res.status(200).json({ message: "Product found.", product });
    } catch (error) {
        console.error("Error:", error.message);
        res.status(500).json({ message: "Internal Server Error" });
    }
});

// Fetch warehouse details endpoint
app.get('/api/warehouses', validateApiKey, async (req, res) => {
    try {
        // Fetch all warehouse details
        const [warehouses] = await db.query('SELECT * FROM Warehouses');

        res.status(200).json({ message: "Warehouses fetched successfully.", warehouses });
    } catch (error) {
        console.error("Error:", error.message);
        res.status(500).json({ message: "Internal Server Error" });
    }
});

// Fetch product quantities endpoint
app.get('/api/product-quantities', validateApiKey, async (req, res) => {
    try {
        // Fetch product quantities in each warehouse
        const [productQuantities] = await db.query('SELECT p.Name AS ProductName, w.Name AS WarehouseName, i.Quantity FROM Inventory i JOIN Products p ON i.ProductID = p.ProductID JOIN Warehouses w ON i.WarehouseID = w.WarehouseID');

        res.status(200).json({ message: "Product quantities fetched successfully.", productQuantities });
    } catch (error) {
        console.error("Error:", error.message);
        res.status(500).json({ message: "Internal Server Error" });
    }
});

// Accept order endpoint
app.post('/api/orders', validateApiKey, async (req, res) => {
    const { customerName, customerPhone, orderFrom, orderDate, deliveryDate, paymentMethod, products, warehouseId } = req.body;

    // Validate order data (you can add more validation logic as needed)

    try {
        // Here you can implement the logic to accept the order and update the inventory
        // Make sure to handle the deduction of quantity from the selected warehouse
        // You can also add additional checks, such as checking if the products are in stock

        // Example implementation:
        // Iterate over each product in the order and update the inventory accordingly
        for (const product of products) {
            const productId = product.productId;
            const quantity = product.quantity;

            // Update inventory in the selected warehouse
            await db.query('UPDATE Inventory SET Quantity = Quantity - ? WHERE ProductID = ? AND WarehouseID = ?', [quantity, productId, warehouseId]);
        }

        // Order accepted successfully
        res.status(201).json({ message: "Order accepted successfully." });
    } catch (error) {
        console.error("Error:", error.message);
        res.status(500).json({ message: "Internal Server Error" });
    }
});
// // Fetch product quantity at warehouse endpoint
app.get('/api/product-quantity', validateApiKey, async (req, res) => {
    const { productId, warehouseId } = req.query;

    if (!productId || !warehouseId) {
        return res.status(400).json({ message: "Product ID and warehouse ID are required." });
    }

    try {
        // Fetch product quantity in the specified warehouse
        const [productQuantity] = await db.query('SELECT Quantity FROM Inventory WHERE ProductID = ? AND WarehouseID = ?', [productId, warehouseId]);

        if (!productQuantity) {
            return res.status(404).json({ message: "Product not found in the specified warehouse." });
        }

        // Extract the quantity value from the result
        const quantity = productQuantity[0].Quantity;

        // Respond with the message and quantity
        res.status(200).json({ message: "Product quantity fetched successfully.", quantity: quantity });
    } catch (error) {
        console.error("Error:", error.message);
        res.status(500).json({ message: "Internal Server Error" });
    }
});

// Registration endpoint
app.post('/api/register', async (req, res) => {
    const { username, password, role } = req.body;

    // Validate username, password, and role
    if (!username || !password || !role) {
        return res.status(400).json({ message: "Username, password, and role are required." });
    }

    try {
        // Check if the username already exists
        const [existingUser] = await db.query('SELECT * FROM Users WHERE Username = ?', [username]);

        // Logging the existing user (for debugging purposes)
        console.log("Existing User:", existingUser);

        if (existingUser) {
            // Log the attempt to register a duplicate user
            console.log("Duplicate registration attempt for username:", username);

            // Return a 409 response indicating that the username already exists
            return res.status(409).json({ message: "Username already exists." });
        }

        // Hash the password
        const hashedPassword = await bcrypt.hash(password, 10);

        // Generate a unique API key
        const apiKey = generateUniqueApiKey();

        // Insert the new user into the database
        await db.query('INSERT INTO Users (Username, Password, Role, APIKey) VALUES (?, ?, ?, ?)', [username, hashedPassword, role, apiKey]);

        // Respond with the generated API key
        res.status(201).json({ message: "User registered successfully.", apiKey });
    } catch (error) {
        console.error("Error:", error.message);
        res.status(500).json({ message: "Internal Server Error" });
    }
});

// Login endpoint
app.post('/api/login', async (req, res) => {
    const { username, password } = req.body;

    // Validate username and password
    if (!username || !password) {
        return res.status(400).json({ message: "Username and password are required." });
    }

    try {
        // Fetch user from the database
        const [user] = await db.query('SELECT * FROM Users WHERE Username = ?', [username]);

        if (!user) {
            return res.status(404).json({ message: "User not found." });
        }

        // Check if the password is correct
        const passwordMatch = await bcrypt.compare(password, user.Password);

        if (!passwordMatch) {
            return res.status(401).json({ message: "Invalid username or password." });
        }

        // User authenticated successfully
        res.status(200).json({ message: "Login successful.", apiKey: user.APIKey });
    } catch (error) {
        console.error("Error:", error.message);
        res.status(500).json({ message: "Internal Server Error" });
    }
});

// Function to generate a unique API key
function generateUniqueApiKey() {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let apiKey = '';
    for (let i = 0; i < 32; i++) {
        apiKey += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return apiKey;
}


// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});


understand this okay