import { Router } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { requireRole } from '../../middleware/rbac.middleware';
import { EVENTS_ROLES } from '../../utils/roles';
import { validate } from '../../middleware/validate';
import { adminCalendarService } from './admin-calendar.service';
import { createAdminViewSchema, updateAdminViewSchema } from './admin-calendar.schemas';
import { dateRangeQuerySchema } from './shared-calendar.schemas';

const router = Router();

router.use(authenticate);
router.use(requireRole(...EVENTS_ROLES));

// List admin calendar views
router.get('/', async (req, res, next) => {
  try {
    const views = await adminCalendarService.listAdminViews(req.user!.id);
    res.json({ views });
  } catch (error) {
    next(error);
  }
});

// Create admin calendar view
router.post('/', validate(createAdminViewSchema), async (req, res, next) => {
  try {
    const view = await adminCalendarService.createAdminView(req.user!.id, req.body);
    res.status(201).json({ view });
  } catch (error) {
    next(error);
  }
});

// Update admin calendar view
router.patch('/:id', validate(updateAdminViewSchema), async (req, res, next) => {
  try {
    const view = await adminCalendarService.updateAdminView(
      req.user!.id,
      req.params.id as string,
      req.body,
    );
    res.json({ view });
  } catch (error) {
    next(error);
  }
});

// Delete admin calendar view
router.delete('/:id', async (req, res, next) => {
  try {
    await adminCalendarService.deleteAdminView(req.user!.id, req.params.id as string);
    res.json({ success: true });
  } catch (error) {
    next(error);
  }
});

// Get merged items for admin calendar view
router.get('/:id/items', validate(dateRangeQuerySchema, 'query'), async (req, res, next) => {
  try {
    const { startDate, endDate } = req.query as { startDate: string; endDate: string };
    const result = await adminCalendarService.getAdminViewItems(
      req.params.id as string,
      req.user!.id,
      startDate,
      endDate,
    );
    res.json(result);
  } catch (error) {
    next(error);
  }
});

export const adminCalendarRouter = router;
