const express = require('express');
const axios = require('axios');
const router = express.Router();
const requireAuth = require('../middleware/requireAuth');
const sanitizeError = require('../utils/sanitizeError');

router.use(requireAuth);

// Get active sessions
router.get('/sessions', async (req, res) => {
  try {
    const response = await axios.get(`${process.env.EMBY_URL}/Sessions`, {
      headers: { 'X-MediaBrowser-Token': process.env.EMBY_API_KEY }
    });
    res.json(response.data);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch Emby sessions', details: sanitizeError(error) });
  }
});

// Get user by ID
router.get('/users/:id', async (req, res) => {
  try {
    const response = await axios.get(`${process.env.EMBY_URL}/Users/${req.params.id}`, {
      headers: { 'X-MediaBrowser-Token': process.env.EMBY_API_KEY }
    });
    res.json(response.data);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch user details', details: sanitizeError(error) });
  }
});

// Get all users
router.get('/users', async (req, res) => {
  try {
    const response = await axios.get(`${process.env.EMBY_URL}/Users`, {
      headers: { 'X-MediaBrowser-Token': process.env.EMBY_API_KEY }
    });
    res.json(response.data);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch users', details: sanitizeError(error) });
  }
});

// Get current user by session ID
router.get('/session/:sessionId/user', async (req, res) => {
  try {
    const response = await axios.get(`${process.env.EMBY_URL}/Sessions`, {
      headers: { 'X-MediaBrowser-Token': process.env.EMBY_API_KEY }
    });
    
    const session = response.data.find(s => s.Id === req.params.sessionId);
    if (!session) {
      return res.status(404).json({ error: 'Session not found' });
    }
    
    const userResponse = await axios.get(`${process.env.EMBY_URL}/Users/${session.UserId}`, {
      headers: { 'X-MediaBrowser-Token': process.env.EMBY_API_KEY }
    });
    
    res.json(userResponse.data);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch user from session', details: sanitizeError(error) });
  }
});

module.exports = router;
