"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express = require("express");
const http_proxy_middleware_1 = require("http-proxy-middleware");
const http_1 = require("http");
const path = require("path");
const app = express();
const PORT = process.env.PROXY_PORT || 9999;
const TARGET_URL = process.env.TARGET_URL;
const BACKEND_PORT = process.env.BACKEND_PORT;
if (!TARGET_URL) {
    console.error('FATAL: TARGET_URL environment variable is not set.');
    process.exit(1);
}
app.get('/repoburg-visual-editor.js', (req, res) => {
    const clientScriptPath = path.resolve(__dirname, '../../client/dist/main.js');
    const options = {
        headers: {
            'Content-Type': 'application/javascript',
        },
    };
    res.sendFile(clientScriptPath, options, (err) => {
        if (err) {
            console.error("Error sending client script:", err);
            res.status(500).send("Could not load client script.");
        }
    });
});
const proxy = (0, http_proxy_middleware_1.createProxyMiddleware)({
    target: TARGET_URL,
    changeOrigin: true,
    selfHandleResponse: true,
    on: {
        proxyRes: (0, http_proxy_middleware_1.responseInterceptor)(async (responseBuffer, proxyRes, req, res) => {
            const contentType = proxyRes.headers['content-type'];
            if (contentType && contentType.includes('text/html')) {
                const html = responseBuffer.toString('utf8');
                const scriptToInject = `<script>window.REPOBURG_BACKEND_PORT = ${BACKEND_PORT};</script><script src="/repoburg-visual-editor.js"></script>`;
                return html.replace('</body>', `${scriptToInject}</body>`);
            }
            return responseBuffer;
        }),
        error: (err, req, res) => {
            console.error('Proxy error:', err);
            if (res instanceof http_1.ServerResponse) {
                if (!res.headersSent) {
                    res.writeHead(500, { 'Content-Type': 'text/plain' });
                }
            }
            res.end('Proxy Error');
        }
    },
});
app.use('/', proxy);
app.listen(PORT, () => {
    console.log(`\nRepoburg Visual Editor is running!`);
    console.log(`- Proxy URL: http://localhost:${PORT}`);
    console.log(`- Target App: ${TARGET_URL}`);
    console.log(`- Backend Port: ${BACKEND_PORT || 'Not Set'}\n`);
});
//# sourceMappingURL=main.js.map