import express from 'express';
import { authenticateToken, optionalAuth } from '../middleware/auth.js';
import notificationService from '../services/NotificationService.js';

const router = express.Router();

/**
 * PHASE 2: Notifications Endpoint (SSE)
 * Provides real-time event streaming for client connections
 */

// Subscribe to events via Server-Sent Events (SSE)
router.get('/events', optionalAuth, (req, res) => {
  // If not authenticated, return 401 (SSE requires user context)
  if (!req.user) {
    return res.status(401).json({
      status: 'error',
      code: 'UNAUTHORIZED',
      message: 'Authentication required for notifications',
      data: null
    });
  }

  const userId = req.user.id;

  // Set headers for SSE
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('X-Accel-Buffering', 'no');

  // Send initial connection confirmation
  res.write(`data: ${JSON.stringify({
    type: 'connection:established',
    timestamp: new Date().toISOString(),
    data: { userId, message: 'Connected to notification stream' }
  })}\n\n`);

  // Register subscriber
  const success = notificationService.subscribe(userId, res);

  if (!success) {
    return res.status(503).json({
      status: 'error',
      code: 'NOTIFICATION_SERVICE_ERROR',
      message: 'Unable to subscribe to notifications',
      data: null
    });
  }

  // Handle client disconnect
  req.on('close', () => {
    console.log(`[Notifications] User ${userId} disconnected from SSE`);
  });
});

// Get notification statistics (admin endpoint)
router.get('/stats', authenticateToken, (req, res) => {
  if (req.user.role !== 'admin') {
    return res.status(403).json({
      status: 'error',
      code: 'FORBIDDEN',
      message: 'Admin access required',
      data: null
    });
  }

  const stats = notificationService.getStats();

  res.status(200).json({
    status: 'success',
    code: 'NOTIFICATION_STATS',
    message: 'Notification service statistics',
    data: stats
  });
});

// Send test notification
router.post('/test', authenticateToken, (req, res) => {
  try {
    const { message = 'Test notification' } = req.body;

    notificationService.broadcast(req.user.id, 'test:message', {
      message,
      userId: req.user.id,
      sentAt: new Date().toISOString()
    });

    res.status(200).json({
      status: 'success',
      code: 'TEST_NOTIFICATION_SENT',
      message: 'Test notification sent',
      data: { timestamp: new Date().toISOString() }
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      code: 'NOTIFICATION_SEND_ERROR',
      message: error.message,
      data: null
    });
  }
});

export default router;
