const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const cors = require('cors');
const cheerio = require('cheerio');

const app = express();
const PORT = process.env.PORT || 3005;

// Allow CORS for all origins
app.use(cors({
    origin: '*', // Adjust this to a specific origin or a whitelist as needed in production
    methods: ['GET', 'POST', 'OPTIONS'], // Allowed methods
    allowedHeaders: ['Content-Type', 'Authorization'], // Custom allowed headers if necessary
}));

// Proxy middleware
app.use('/proxy', (req: any, res: any, next: any) => {
    const targetUrl = req.query.url; // Get target URL from query parameters

    if (!targetUrl) {
        return res.status(400).send('No target URL provided');
    }

    const proxy = createProxyMiddleware({
        target: targetUrl,
        changeOrigin: true,
        selfHandleResponse: true,
        onProxyRes: (proxyRes: any, req: any, res: any) => {
          console.log('on proxy res');
            const contentType = proxyRes.headers['content-type'];
            if (contentType && contentType.includes('text/html')) {
                let body = '';
                proxyRes.on('data', (chunk: any) => {
                    body += chunk.toString();
                });

                proxyRes.on('end', () => {
                    const $ = cheerio.load(body);

                    // Modify internal links
                    $('a').each((i: any, link: any) => {
                        const href = $(link).attr('href');
                        if (href && !href.startsWith('http')) {
                            $(link).attr('href', `/proxy?url=${encodeURIComponent(new URL(href, targetUrl).href)}`);
                        }
                    });

                    // Modify forms
                    $('form').each((i: any, form: any) => {
                        const action = $(form).attr('action');
                        if (action) {
                            $(form).attr('action', `/proxy?url=${encodeURIComponent(new URL(action, targetUrl).href)}`);
                        }
                    });

                    // Send the modified HTML back to the client
                    res.setHeader('Content-Type', 'text/html');
                    res.send($.html());
                });
            } else {
                // Pipe the response directly if it's not HTML
                res.setHeader('Access-Control-Allow-Origin', '*'); // CORS for non-HTML responses
                proxyRes.pipe(res);
            }
        },
        onError(err: any, req: any, res: any) {
            res.status(500).send('Proxy error');
        },
    });

    return proxy(req, res, next);
});

// Handle preflight requests for CORS
app.options('/proxy', cors()); // Enable pre-flight for the proxy endpoint

app.listen(PORT, () => {
    console.log(`Proxy server is running on http://localhost:${PORT}`);
});