import type { Express } from 'express';
import type { IncomingMessage, Server as HttpServer, ServerResponse } from 'http';
import type { Socket } from 'net';
import httpProxy from 'http-proxy';
import type { ClientRequest } from 'http';

const LIVEKIT_TARGET = (
  process.env.LIVEKIT_SERVER_URL || 'ws://127.0.0.1:7880'
).replace(/^ws(s?):\/\//, 'http$1://');

const proxy = httpProxy.createProxyServer({
  target: LIVEKIT_TARGET,
  ws: true,
  changeOrigin: false,
  xfwd: true,
});

proxy.on('error', (err: Error, req: IncomingMessage, res: ServerResponse | Socket) => {
  console.error('[livekit-proxy] error:', err.message, req?.url);
  if (res && 'writeHead' in res && !res.headersSent) {
    res.writeHead(502, { 'Content-Type': 'text/plain' });
    res.end('LiveKit proxy error');
  }
});

proxy.on('proxyReqWs', (proxyReq: ClientRequest, req: IncomingMessage) => {
  const host = req.headers.host || 'socket.iue.co.th';
  proxyReq.setHeader('X-Forwarded-Host', host);
  proxyReq.setHeader('X-Forwarded-Proto', 'https');
});

function stripLiveKitPrefix(url: string): string {
  const rewritten = url.replace(/^\/livekit/, '') || '/';
  return rewritten.startsWith('/') ? rewritten : `/${rewritten}`;
}

/** Proxy /livekit/* → LiveKit :7880 (http-proxy โดยตรง — เสถียรกว่า middleware) */
export function mountLiveKitProxy(app: Express, httpServer: HttpServer): void {
  app.use('/livekit', (req, res) => {
    const saved = req.url;
    req.url = stripLiveKitPrefix(saved);
    proxy.web(req, res, { target: LIVEKIT_TARGET }, (err: Error) => {
      if (err) {
        console.error('[livekit-proxy] web:', err.message);
        if (!res.headersSent) {
          res.status(502).send('LiveKit proxy error');
        }
      }
    });
    req.url = saved;
  });

  httpServer.on('upgrade', (req, socket, head) => {
    if (!(req.url || '').startsWith('/livekit')) {
      return;
    }
    const saved = req.url || '/';
    req.url = stripLiveKitPrefix(saved);
    console.log('[livekit-proxy] ws upgrade →', req.url.slice(0, 80));
    proxy.ws(req, socket as Socket, head, { target: LIVEKIT_TARGET });
    req.url = saved;
  });
}
