const axios = require('axios');

const targetUrl = process.env.TARGET_URL;
const proxyUrl = process.env.PROXY_URL;

const apiProxy = async (req, res, next) => {
    if (req.originalUrl.startsWith('/wp-json/tukutema/v1/')) {
        try {
            const requestedPath = req.originalUrl.substring(1);
            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 || '',
                // Header CORS
                'Access-Control-Allow-Origin': proxyUrl,
                'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
                'Access-Control-Allow-Headers': 'Content-Type, X-HTTP-Method-Override',
                'Access-Control-Allow-Credentials': true,
            };

            // Menangani permintaan OPTIONS (preflight)
            if (req.method === 'OPTIONS') {
                res.header('Access-Control-Allow-Origin', proxyUrl);
                res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
                res.header('Access-Control-Allow-Headers', 'Content-Type, X-HTTP-Method-Override');
                res.header('Access-Control-Allow-Credentials', true);
                return res.status(200).send();
            }

            // Menangani permintaan GET dan POST
            const response = await axios({
                method: req.method,
                url: fullTargetUrl,
                headers: requestHeaders,
                data: req.body,
            });

            // Meneruskan respons API ke browser
            res.status(response.status).set(response.headers).send(response.data);

        } catch (error) {
            res.status(error.response?.status || 500).send(error.message);
        }
    } else {
        next();
    }
};

module.exports = apiProxy;