import https from 'https';
import http from 'http';
import fs from 'fs';

const options = {
  key: fs.readFileSync('./localhost+2-key.pem'),
  cert: fs.readFileSync('./localhost+2.pem')
};

const server = https.createServer(options, (req, res) => {
  // Handle CORS
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  
  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
    return;
  }

  // Proxy to the development server but modify redirect responses
  const proxyReq = http.request({
    hostname: 'localhost',
    port: 3000,
    path: req.url,
    method: req.method,
    headers: {
      ...req.headers,
      host: 'localhost:3000'
    }
  }, (proxyRes) => {
    // Copy headers but modify location if it's a redirect
    const headers = { ...proxyRes.headers };
    
    if (headers.location && headers.location.includes('localhost:3001')) {
      headers.location = headers.location.replace('localhost:3001', '159.195.9.107:3443');
      console.log('🔄 Fixed redirect:', headers.location);
    }
    
    res.writeHead(proxyRes.statusCode, headers);
    proxyRes.pipe(res);
  });

  req.pipe(proxyReq);
  
  proxyReq.on('error', (err) => {
    console.error('Proxy error:', err);
    res.writeHead(500);
    res.end('Proxy Error');
  });
});

server.listen(3443, '0.0.0.0', () => {
  console.log('Fixed HTTPS Proxy running on https://159.195.9.107:3443');
  console.log('This will fix localhost:3001 redirects automatically');
});
