import { Router } from 'express';
import { authenticate } from '../../../middleware/auth.middleware';
import { requireRole } from '../../../middleware/rbac.middleware';
import { validate } from '../../../middleware/validate';
import { ShiftSeriesService } from './shift-series.service';
import { createShiftSeriesSchema, updateShiftSeriesSchema } from './shift-series.schemas';
import { SCHEDULING_ROLES } from '../../../utils/roles';

const router = Router();

// All routes require admin role
router.use(authenticate, requireRole(...SCHEDULING_ROLES));

// Create series
router.post(
  '/',
  validate(createShiftSeriesSchema),
  async (req, res, next) => {
    try {
      const result = await ShiftSeriesService.createSeries(
        req.body,
        req.user?.id
      );
      res.json(result);
    } catch (error) {
      next(error);
    }
  }
);

// Get series shift count
router.get('/:id/count', async (req, res, next) => {
  try {
    const count = await ShiftSeriesService.getShiftCount(req.params.id as string);
    res.json({ count });
  } catch (error) {
    next(error);
  }
});

// Get series
router.get('/:id', async (req, res, next) => {
  try {
    const series = await ShiftSeriesService.getSeries(req.params.id as string);
    res.json({ series });
  } catch (error) {
    next(error);
  }
});

// Update series
router.put(
  '/:id',
  validate(updateShiftSeriesSchema),
  async (req, res, next) => {
    try {
      const series = await ShiftSeriesService.updateSeries(
        req.params.id as string,
        req.body
      );
      res.json({ series });
    } catch (error) {
      next(error);
    }
  }
);

// Delete series
router.delete('/:id', async (req, res, next) => {
  try {
    await ShiftSeriesService.deleteSeries(req.params.id as string);
    res.json({ success: true });
  } catch (error) {
    next(error);
  }
});

export default router;
