import { Router, Request, Response, NextFunction } from 'express';
import { geocodeQueueService } from '../../../services/geocode-queue.service';
import { bulkGeocodeSchema } from './bulk-geocode.schemas';
import { validate } from '../../../middleware/validate';
import { authenticate } from '../../../middleware/auth.middleware';
import { requireRole } from '../../../middleware/rbac.middleware';
import { MAP_ROLES } from '../../../utils/roles';

const router = Router();
router.use(authenticate);
router.use(requireRole(...MAP_ROLES));

// POST /api/map/locations/bulk-geocode — start bulk geocoding job
router.post(
  '/',
  validate(bulkGeocodeSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const jobId = await geocodeQueueService.startBulkGeocode(req.user!.id, req.body);
      res.json({ jobId, message: 'Bulk geocoding job started' });
    } catch (err) {
      next(err);
    }
  }
);

// GET /api/map/locations/bulk-geocode/:jobId — get job status
router.get('/:jobId', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const status = await geocodeQueueService.getJobStatus(req.params.jobId as string);
    res.json(status);
  } catch (err) {
    next(err);
  }
});

// GET /api/map/locations/bulk-geocode/stats — queue statistics
router.get('/stats', async (_req: Request, res: Response, next: NextFunction) => {
  try {
    const stats = await geocodeQueueService.getStats();
    res.json(stats);
  } catch (err) {
    next(err);
  }
});

export { router as bulkGeocodeRouter };
