import http from 'http';
import { WebSocketServer } from 'ws';
import { config } from './config.js';

export function createHttpAndWs({ onConnection, getStatus }) {
  const server = http.createServer((req, res) => {
    if (req.url === '/health') {
      const status = getStatus();
      const ok = status?.ok !== false;
      res.writeHead(ok ? 200 : 503, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(status));
      return;
    }
    res.writeHead(404);
    res.end('Not found');
  });

  const wss = new WebSocketServer({
    server,
    maxPayload: 1024 * 16,
  });

  wss.on('connection', (ws, req) => {
    // basic origin check
    const origin = req.headers.origin;
    if (config.allowedOrigins.length && origin && !config.allowedOrigins.includes(origin)) {
      ws.close(1008, 'Invalid origin');
      return;
    }
    onConnection(ws, req);
  });

  return { server, wss };
}
