const express = require('express');
const serveStatic = require('serve-static');
const { default: SseStream } = require('ssestream');

const app = express();

// Parse typical POST bodies from clients (object / JSON string / raw buffer)
app.use(express.json({ limit: '2mb' }));
app.use(express.text({ type: ['text/*', 'application/json'], limit: '2mb' }));
app.use(express.raw({ type: 'application/octet-stream', limit: '2mb' }));

app.use(serveStatic(__dirname));

function logBodyForDebug(req) {
  const body = req.body;
  if (body === undefined || body === null) {
    console.log('Body: <empty>');
    return;
  }
  if (Buffer.isBuffer(body)) {
    console.log('Body (Buffer) length:', body.length);
    console.log('Body (Buffer) hex:', body.toString('hex'));
    return;
  }
  if (typeof body === 'string') {
    console.log('Body (string):', body);
    return;
  }
  console.log('Body (object):', JSON.stringify(body, null, 2));
}

function startSse(req, res) {
  console.log('new connection', req.method);
  console.log('URL:', req.url);
  console.log('Headers:', JSON.stringify(req.headers, null, 2));
  console.log('Query parameters:', JSON.stringify(req.query, null, 2));
  if (req.method === 'POST') {
    logBodyForDebug(req);
  }

  // Prefer SSE content type (some clients still accept octet-stream for streaming)
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  const sseStream = new SseStream(req);
  sseStream.pipe(res);
  const pusher = setInterval(() => {
    sseStream.write({
      event: 'server-time',
      data: new Date().toTimeString()
    });
  }, 2000);
  res.on('close', () => {
    console.log('lost connection');
    clearInterval(pusher);
    sseStream.unpipe(res);
  });
}

app.get('/sse', (req, res) => {
  startSse(req, res);
})

app.post('/sse', (req, res) => {
  startSse(req, res);
})

const PORT = process.env.PORT || 9000;
app.listen(PORT, '0.0.0.0', (err) => {
  if (err) throw err;
  console.log(`server ready on http://0.0.0.0:${PORT}`);
})