import { Router } from 'express';
import { authenticate } from '../../../middleware/auth.middleware';
import { requireRole } from '../../../middleware/rbac.middleware';
import { validate } from '../../../middleware/validate';
import { smsTemplatesService } from './sms-templates.service';
import { createSmsTemplateSchema, updateSmsTemplateSchema } from './sms-templates.schemas';
import { BROADCAST_ROLES } from '../../../utils/roles';

const router = Router();

// All routes require authentication + broadcast admin role
router.use(authenticate, requireRole(...BROADCAST_ROLES));

// GET /api/sms/templates — list with search/filter/pagination
router.get('/', async (req, res, next) => {
  try {
    const page = Math.max(1, Number(req.query.page) || 1);
    const limit = Math.min(100, Math.max(1, Number(req.query.limit) || 50));
    const search = req.query.search as string | undefined;
    const category = req.query.category as string | undefined;
    const isFavorite = req.query.isFavorite as string | undefined;
    const result = await smsTemplatesService.findAll({ page, limit, search, category, isFavorite });
    res.json(result);
  } catch (err) { next(err); }
});

// GET /api/sms/templates/:id — single template with computed fields
router.get('/:id', async (req, res, next) => {
  try {
    const template = await smsTemplatesService.findById(req.params.id as string);
    if (!template) { res.status(404).json({ error: 'Template not found' }); return; }
    res.json(template);
  } catch (err) { next(err); }
});

// POST /api/sms/templates — create template
router.post('/', validate(createSmsTemplateSchema), async (req, res, next) => {
  try {
    const template = await smsTemplatesService.create(req.body, req.user!.id);
    res.status(201).json(template);
  } catch (err) { next(err); }
});

// PUT /api/sms/templates/:id — update template
router.put('/:id', validate(updateSmsTemplateSchema), async (req, res, next) => {
  try {
    const template = await smsTemplatesService.update(req.params.id as string, req.body);
    res.json(template);
  } catch (err) { next(err); }
});

// DELETE /api/sms/templates/:id — delete (system-protected)
router.delete('/:id', async (req, res, next) => {
  try {
    await smsTemplatesService.delete(req.params.id as string);
    res.json({ success: true });
  } catch (err) { next(err); }
});

// POST /api/sms/templates/:id/favorite — toggle favorite
router.post('/:id/favorite', async (req, res, next) => {
  try {
    const template = await smsTemplatesService.toggleFavorite(req.params.id as string);
    res.json(template);
  } catch (err) { next(err); }
});

export const smsTemplatesRouter = router;
