/**
 * Session Management REST API
 * Provides unified session listing, abort, delete, and stats endpoints.
 * All endpoints filter by userId for user isolation.
 */

import { Router } from 'express';
import {
  getAllActiveSessions,
  checkSessionStatus,
  abortSession,
  abortAllSessions,
  getSessionStats,
} from '../services/sessionRegistry.js';

const router = Router();

// Helper: get sessions owned by the current user
function getUserSessions(req) {
  const userId = req.user?.id || req.user?.userId;
  const sessionOwners = req.sessionOwners;
  const all = getAllActiveSessions();
  if (!userId || !sessionOwners) return all; // local mode, no filtering
  return all.filter(s => {
    const owner = sessionOwners.get(s.sessionId);
    return !owner || owner === userId; // include if no owner (legacy) or owned by user
  });
}

/**
 * GET /api/sessions — List active sessions for this user
 */
router.get('/', (req, res) => {
  try {
    const sessions = getUserSessions(req);
    res.json({ sessions });
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch sessions' });
  }
});

/**
 * GET /api/sessions/stats — Session counts for this user
 */
router.get('/stats', (req, res) => {
  try {
    const sessions = getUserSessions(req);
    const byProvider = { claude: 0, cursor: 0, codex: 0 };
    for (const s of sessions) {
      byProvider[s.provider] = (byProvider[s.provider] || 0) + 1;
    }
    res.json({
      total: sessions.length,
      active: sessions.filter(s => s.status === 'active').length,
      byProvider,
    });
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch session stats' });
  }
});

/**
 * GET /api/sessions/:sessionId — Get session details (only if owned)
 */
router.get('/:sessionId', (req, res) => {
  try {
    const { sessionId } = req.params;
    const userId = req.user?.id || req.user?.userId;
    const sessionOwners = req.sessionOwners;

    // Check ownership
    if (userId && sessionOwners) {
      const owner = sessionOwners.get(sessionId);
      if (owner && owner !== userId) {
        return res.status(403).json({ error: 'Access denied' });
      }
    }

    const status = checkSessionStatus(sessionId);
    if (!status.active) {
      return res.status(404).json({ error: 'Session not found or inactive' });
    }

    res.json({
      sessionId,
      provider: status.provider,
      active: status.active,
    });
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch session details' });
  }
});

/**
 * POST /api/sessions/:sessionId/abort — Abort an active session (only if owned)
 */
router.post('/:sessionId/abort', async (req, res) => {
  try {
    const { sessionId } = req.params;
    const { provider } = req.body || {};
    const userId = req.user?.id || req.user?.userId;
    const sessionOwners = req.sessionOwners;

    // Check ownership before aborting
    if (userId && sessionOwners) {
      const owner = sessionOwners.get(sessionId);
      if (owner && owner !== userId) {
        return res.status(403).json({ error: 'Access denied — cannot abort another user\'s session' });
      }
    }

    const result = await abortSession(sessionId, provider);
    if (!result.aborted) {
      return res.status(404).json({ error: 'Session not found or already terminated' });
    }

    res.json({ success: true, sessionId, provider: result.provider });
  } catch (error) {
    res.status(500).json({ error: 'Failed to abort session' });
  }
});

/**
 * POST /api/sessions/abort-all — Abort all active sessions owned by this user
 */
router.post('/abort-all', async (req, res) => {
  try {
    const userSessions = getUserSessions(req);
    const results = [];

    for (const s of userSessions) {
      const { aborted } = await abortSession(s.sessionId, s.provider);
      results.push({ sessionId: s.sessionId, provider: s.provider, aborted });
    }

    res.json({
      success: true,
      aborted: results.filter(r => r.aborted).length,
      results,
    });
  } catch (error) {
    res.status(500).json({ error: 'Failed to abort sessions' });
  }
});

export default router;
