import { WebSocketServer } from 'ws';
import { rawQuery } from '../db.js';
import { optionsFlowQuery } from '../queries/optionsFlowQuery.js';

export function setupWebSocket(server) {
  const wss = new WebSocketServer({ server, path: '/ws/flow' });
  
  wss.on('connection', (ws) => {
    console.log('Client connected to WebSocket');
    
    // Send initial data
    sendFlowUpdate(ws);
    
    // Set up auto-refresh (every 30 seconds)
    const interval = setInterval(() => {
      if (ws.readyState === ws.OPEN) {
        sendFlowUpdate(ws);
      }
    }, 120000);
    
    ws.on('close', () => {
      clearInterval(interval);
      console.log('Client disconnected');
    });
  });
  
  return wss;
}

async function sendFlowUpdate(ws) {
  try {
    const today = new Date().toISOString().split('T')[0];
    const data = await rawQuery(optionsFlowQuery, [today, today]);
    
    ws.send(JSON.stringify({
      type: 'FLOW_UPDATE',
      data,
      timestamp: new Date().toISOString()
    }));
  } catch (error) {
    console.error('WebSocket update error:', error);
  }
}
