import { Router } from 'express';
import { authenticate } from '../../../middleware/auth.middleware';
import { requireRole } from '../../../middleware/rbac.middleware';
import { smsDeviceService } from './sms-device.service';
import { termuxClient } from '../../../services/termux.client';
import { BROADCAST_ROLES } from '../../../utils/roles';

const router = Router();

router.use(authenticate, requireRole(...BROADCAST_ROLES));

// GET /api/sms/device — latest device status
router.get('/', async (_req, res, next) => {
  try {
    const status = await smsDeviceService.getStatus();
    res.json(status);
  } catch (err) { next(err); }
});

// GET /api/sms/device/history — device status history
router.get('/history', async (req, res, next) => {
  try {
    const limit = Math.min(100, Math.max(1, Number(req.query.limit) || 50));
    const history = await smsDeviceService.getHistory(limit);
    res.json(history);
  } catch (err) { next(err); }
});

// GET /api/sms/device/live — live device info directly from Termux
router.get('/live', async (_req, res, next) => {
  try {
    const info = await smsDeviceService.getLiveInfo();
    res.json(info);
  } catch (err) { next(err); }
});

// POST /api/sms/device/sync — trigger immediate response sync
router.post('/sync', async (_req, res, next) => {
  try {
    const result = await smsDeviceService.triggerSync();
    res.json(result);
  } catch (err) { next(err); }
});

// GET /api/sms/device/logs — tail phone API server logs
router.get('/logs', async (req, res, next) => {
  try {
    const lines = Math.min(500, Math.max(1, Number(req.query.lines) || 100));
    const logs = await termuxClient.getLogs(lines);
    if (!logs) {
      res.status(503).json({ error: 'Phone not connected or SMS not enabled' });
      return;
    }
    res.json(logs);
  } catch (err) { next(err); }
});

export const smsDeviceRouter = router;
