const express = require('express');
const axios = require('axios');
const router = express.Router();

const targetUrl = process.env.TARGET_URL;
const AXIOS_TIMEOUT = process.env.TARGET_TIMEOUT ? parseInt(process.env.TARGET_TIMEOUT) : 15000; 

const MAX_RETRIES = 5;
const RETRY_DELAY = 5000; 

const fetchWithRetry = async (fullTargetUrl, headers, retries = MAX_RETRIES) => {
    try {
        const response = await axios.get(fullTargetUrl, { headers, timeout: AXIOS_TIMEOUT });
        
        if (response.status === 200 && response.headers['content-type'] && response.headers['content-type'].includes('text/html')) {
            return { html: response.data, headers: response.headers, status: response.status };
        } else {
            throw new Error(`Invalid response status/content-type: ${response.status} (${response.headers['content-type']})`);
        }
    } catch (error) {
        if (retries > 0) {
            const delay = RETRY_DELAY * (MAX_RETRIES - retries + 1);
            console.warn(`[Async Fetch] Gagal mengambil ${fullTargetUrl}. Status/Code: ${error.response?.status || error.code}. Mencoba ulang dalam ${delay / 1000}s. Sisa retry: ${retries - 1}`);
            await new Promise(resolve => setTimeout(resolve, delay));

            return fetchWithRetry(fullTargetUrl, headers, retries - 1);
        } else {
            console.error(`[Async Fetch] Gagal setelah ${MAX_RETRIES} percobaan untuk ${fullTargetUrl}`);
            throw new Error('Gagal mengambil konten setelah maksimal percobaan.');
        }
    }
};

module.exports.fetchWithRetry = fetchWithRetry;


router.get('/async-fetch/*', async (req, res) => {
    const requestedPath = req.params[0] || req.url.substring('/async-fetch/'.length);
    const fullTargetUrl = `${targetUrl}${requestedPath}`;

    const requestHeaders = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Cookie': req.headers.cookie || ''
    };

    try {
        const { html, headers } = await fetchWithRetry(fullTargetUrl, requestHeaders);

        res.status(200).set('Content-Type', 'text/html').send(html);

    } catch (error) {
        res.status(503).send(`<html><head></head><body>${error.message || 'Gagal mengambil data.'}</body></html>`);
    }
});

module.exports.router = router;
