import { Router, Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { geocodingService } from './geocoding.service';
import { validate } from '../../../middleware/validate';
import { authenticate } from '../../../middleware/auth.middleware';
import { requireRole } from '../../../middleware/rbac.middleware';
import { MAP_ROLES } from '../../../utils/roles';

const searchSchema = z.object({
  q: z.string().min(2, 'Query must be at least 2 characters'),
  limit: z.coerce.number().int().min(1).max(10).default(5),
});

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

// GET /api/map/geocoding/search?q=Ottawa&limit=5
router.get(
  '/search',
  validate(searchSchema, 'query'),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const { q, limit } = req.query as unknown as { q: string; limit: number };
      const results = await geocodingService.search(q, limit);
      res.json(results);
    } catch (err) {
      next(err);
    }
  },
);

export { router as geocodingRouter };
