const axios = require('axios');
const targetUrl = process.env.TARGET_URL;

const assetProxy = async (req, res, next) => {
    let assetPath = req.url; 
    
    const queryIndex = assetPath.indexOf('?');
    if (queryIndex !== -1) {
        assetPath = assetPath.substring(0, queryIndex);
    }
    
    let assetUrl; 
    
    if (/\.(css|js|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$/i.test(assetPath)) {
        try {
            assetUrl = `${targetUrl}${assetPath}`; 
            
            const response = await axios.get(assetUrl, {
                responseType: 'arraybuffer',
                timeout: 50000, // 50 detik
                headers: {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36',
                    'Referer': targetUrl, 
                    'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Cookie': req.headers.cookie || '' 
                }
            });
            
            delete response.headers['content-encoding']; 
            delete response.headers['transfer-encoding'];

            res.status(response.status).set(response.headers).send(response.data);
            return;
            
        } catch (error) {
            if (error.response) {
                const status = error.response.status;
                
                if (status === 404) {
                    return res.status(404).send('Asset not found on target server.'); 
                } 
                if (status === 403) {
                    return res.status(403).send('Asset access forbidden by target server.'); 
                }
                
                return res.status(status).send(`Request to target failed with status ${status}.`);
                
            } else if (error.code === 'ETIMEDOUT') {
                 return res.status(504).send('Gateway Timeout during asset fetch.');

            } else {
                return res.status(500).send('Proxy connection error.');
            }
        }
    }
    next();
};

module.exports = assetProxy;