var express = require('express');
var router = express.Router();
var db = require('../db/database');
var { authMiddleware } = require('../middleware/auth');

router.use(authMiddleware);

// List all sessions for current user
router.get('/', async function(req, res) {
  try {
    var sessions = await db.all(
      'SELECT id, ip_address, device_label, created_at, last_activity FROM user_sessions WHERE user_id = ? ORDER BY last_activity DESC',
      [req.user.id]
    );
    res.json({ success: true, sessions: sessions, currentSessionId: req.sessionId || null });
  } catch (e) {
    res.status(500).json({ error: 'Request failed' });
  }
});

// Revoke a specific session
router.delete('/:id', async function(req, res) {
  try {
    if (req.params.id === req.sessionId) {
      return res.status(400).json({ error: 'Cannot revoke your current session. Use logout instead.' });
    }
    var result = await db.run(
      'DELETE FROM user_sessions WHERE id = ? AND user_id = ?',
      [req.params.id, req.user.id]
    );
    if (result.changes === 0) return res.status(404).json({ error: 'Session not found' });
    res.json({ success: true });
  } catch (e) {
    res.status(500).json({ error: 'Request failed' });
  }
});

// Revoke all other sessions
router.delete('/', async function(req, res) {
  try {
    if (!req.sessionId) return res.status(400).json({ error: 'Current session not identified. Log out and log back in.' });
    var result = await db.run(
      'DELETE FROM user_sessions WHERE user_id = ? AND id != ?',
      [req.user.id, req.sessionId]
    );
    res.json({ success: true, revoked: result.changes });
  } catch (e) {
    res.status(500).json({ error: 'Request failed' });
  }
});

module.exports = router;
