import { Router } from 'express';
import { env } from '../config/env.js';
import { AppError } from '../middleware/errorHandler.js';

const router = Router();

router.get('/autocomplete', async (req, res, next) => {
  try {
    const { input } = req.query;
    if (!input || typeof input !== 'string' || input.length < 2) {
      return res.json({ predictions: [] });
    }

    const apiKey = env.GOOGLE_MAPS_API_KEY;
    if (!apiKey) throw new AppError(500, 'Google Maps API key not configured');

    const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${encodeURIComponent(input)}&types=(cities)&key=${apiKey}`;
    const response = await fetch(url);
    const data = await response.json() as { predictions: Array<{ description: string; place_id: string }> };

    const predictions = (data.predictions || []).map((p: { description: string; place_id: string }) => ({
      description: p.description,
      placeId: p.place_id,
    }));

    res.json({ predictions });
  } catch (error) {
    next(error);
  }
});

router.get('/details', async (req, res, next) => {
  try {
    const { placeId } = req.query;
    if (!placeId || typeof placeId !== 'string') {
      throw new AppError(400, 'Place ID is required');
    }

    const apiKey = env.GOOGLE_MAPS_API_KEY;
    if (!apiKey) throw new AppError(500, 'Google Maps API key not configured');

    const url = `https://maps.googleapis.com/maps/api/place/details/json?place_id=${encodeURIComponent(placeId)}&fields=formatted_address,geometry&key=${apiKey}`;
    const response = await fetch(url);
    const data = await response.json() as { result: { formatted_address: string; geometry: { location: { lat: number; lng: number } } } };

    if (!data.result) throw new AppError(404, 'Place not found');

    res.json({
      address: data.result.formatted_address,
      lat: data.result.geometry.location.lat,
      lng: data.result.geometry.location.lng,
    });
  } catch (error) {
    next(error);
  }
});

export default router;
