import { Router } from 'express';
import { authenticate } from '../../../middleware/auth.middleware';
import { requireRole } from '../../../middleware/rbac.middleware';
import { smsSendRateLimit } from '../../../middleware/rate-limit';
import { smsMessagesService } from './sms-messages.service';
import { eventBus } from '../../../services/event-bus.service';
import { BROADCAST_ROLES } from '../../../utils/roles';

const MAX_SMS_LENGTH = 1600;
const PHONE_DIGITS_RE = /^\d{10,11}$/;

const router = Router();

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

// GET /api/sms/messages — list all messages
router.get('/', async (req, res, next) => {
  try {
    const page = Math.max(1, Number(req.query.page) || 1);
    const limit = Math.min(200, Math.max(1, Number(req.query.limit) || 50));
    const result = await smsMessagesService.findAll({
      page,
      limit,
      direction: req.query.direction as string | undefined,
      phone: req.query.phone as string | undefined,
    });
    res.json(result);
  } catch (err) { next(err); }
});

// GET /api/sms/messages/followups — messages needing follow-up
router.get('/followups', async (_req, res, next) => {
  try {
    const messages = await smsMessagesService.getFollowups();
    res.json(messages);
  } catch (err) { next(err); }
});

// POST /api/sms/messages/send — send ad-hoc SMS
router.post('/send', smsSendRateLimit, async (req, res, next) => {
  try {
    const { phone, message } = req.body as { phone?: string; message?: string };
    if (!phone || !message) {
      res.status(400).json({ error: { message: 'Phone and message are required', code: 'VALIDATION_ERROR' } });
      return;
    }
    const digits = phone.replace(/\D/g, '');
    if (!PHONE_DIGITS_RE.test(digits)) {
      res.status(400).json({ error: { message: 'Invalid phone number format', code: 'VALIDATION_ERROR' } });
      return;
    }
    if (message.length > MAX_SMS_LENGTH) {
      res.status(400).json({ error: { message: `Message too long (max ${MAX_SMS_LENGTH} characters)`, code: 'VALIDATION_ERROR' } });
      return;
    }
    const result = await smsMessagesService.sendSingle(phone, message);

    eventBus.publish('sms.message.sent', {
      messageId: result.id,
      phone: result.phone,
      body: result.message,
    });

    res.json(result);
  } catch (err) { next(err); }
});

export const smsMessagesRouter = router;
