import express from 'express';
import { requireAuth } from '../middleware/auth.js';

const router = express.Router();

router.use(requireAuth);

const CAPTURE_URL = process.env.CAPTURE_URL || 'http://capture:3001';

// Helper to proxy requests
const proxyRequest = async (method, path, body = null) => {
  const options = {
    method,
    headers: {
      'Content-Type': 'application/json',
    },
  };

  if (body) {
    options.body = JSON.stringify(body);
  }

  try {
    const response = await fetch(`${CAPTURE_URL}${path}`, options);
    const data = await response.json();
    return { status: response.status, data };
  } catch (err) {
    console.error('Capture service error:', err);
    throw err;
  }
};

// POST /start - Forward start request
router.post('/start', async (req, res, next) => {
  try {
    const { status, data } = await proxyRequest('POST', '/start', req.body);
    res.status(status).json(data);
  } catch (err) {
    next(err);
  }
});

// POST /stop - Forward stop request
router.post('/stop', async (req, res, next) => {
  try {
    const { status, data } = await proxyRequest('POST', '/stop', req.body);
    res.status(status).json(data);
  } catch (err) {
    next(err);
  }
});

// GET /status - Forward status request
router.get('/status', async (req, res, next) => {
  try {
    const { status, data } = await proxyRequest('GET', '/status');
    res.status(status).json(data);
  } catch (err) {
    next(err);
  }
});

// GET /devices - Forward devices request
router.get('/devices', async (req, res, next) => {
  try {
    const { status, data } = await proxyRequest('GET', '/devices');
    res.status(status).json(data);
  } catch (err) {
    next(err);
  }
});

export default router;
