// const AllowedIPs = require('../models/AllowedIPs'); // Adjust path based on your project structure
const db = require('../config/db.config');
const axios = require('axios')
exports.ipLockMiddleware = async (req, res, next) => {
    try {
        // const clientIP = req.headers['x-forwarded-for']?.split(',')[0] || req.socket.remoteAddress;
        async function getPublicIP() {
            try {
                const response = await axios.get('https://api64.ipify.org?format=json');
                return response.data.ip; // Returns public IP
            } catch (error) {
                console.error('Error fetching public IP:', error);
                return null;
            }
        }
        let clientIP = req.headers['x-forwarded-for']
            ? req.headers['x-forwarded-for'].split(',')[0].trim()
            : req.socket.remoteAddress;

        // If running locally and the IP is `::1` or `127.0.0.1`, fetch the external IP
        if (clientIP === '::1' || clientIP === '127.0.0.1') {
            clientIP = await getPublicIP();
        }
        // const clientIP = await getPublicIP();
        // const clientIP = (req.headers['x-forwarded-for'] || req.connection.remoteAddress).split(',')[0].trim();

        // Fetch allowed IPs from the database
        // const allowedIPs = await AllowedIPs.findAll({ attributes: ['ip'] });
        // const allowedIPList = allowedIPs.map(ipRecord => ipRecord.ip);
        const allowedIPsQuery = await db.query(
            "SELECT ip FROM allowedIps",
            { type: db.QueryTypes.SELECT }
        );

        const allowedIPList = allowedIPsQuery.map(ipRecord => ipRecord.ip);
        console.log(allowedIPList, clientIP)
        if (allowedIPList.includes(clientIP)) {
            return next(); // Allow request
        } else {
            return res.status(403).json({ error: "Access denied: Unauthorized IP" });
        }
    } catch (error) {
        console.error("Error in IP Lock Middleware:", error);
        return res.status(500).json({ error: "Internal server error" });
    }
};

