/**
 * Phase 8.11b (2026-04-29) — Service de query OSM Overpass API.
 *
 * Utilisé par ParkingSlotGeneratorService pour récupérer les segments
 * routiers autour du territoire (rayon 100m) afin de générer les slots
 * de parking auto le long des rues.
 *
 * Spec user : "around: 100" (100m de rayon autour du territoire).
 *
 * Endpoint : https://overpass-api.de/api/interpreter
 * Rate limit : ~10000 req/jour (largement suffisant — 1 req par territoire,
 * cache permanent en DB après génération).
 *
 * Latence : ~1-3s par query — acceptable pour génération one-time au
 * premier achat de véhicule (ou regen explicite si territoire bouge).
 */

const OVERPASS_URL = 'https://overpass-api.de/api/interpreter';

export interface OsmWay {
  id: number;
  /** Liste des points GPS qui composent la rue (polyligne). */
  geometry: Array<{ lat: number; lon: number }>;
  /** Tags OSM (highway type, name, etc.). */
  tags: Record<string, string>;
}

export class OsmRoadService {

  /**
   * Query Overpass pour récupérer toutes les rues "drivables" dans un rayon
   * autour d'un point GPS. Filtre highway IN (residential|primary|secondary|
   * tertiary|unclassified) — exclut autoroutes/pédestres/pistes cyclables.
   *
   * Returns la liste de OsmWay avec leur polyligne complète (out geom).
   * Throws si Overpass timeout ou rate-limited (le caller peut retry).
   */
  static async fetchRoadsAround(lat: number, lon: number, radiusM = 100): Promise<OsmWay[]> {
    const query = `
      [out:json][timeout:25];
      (
        way["highway"~"^(residential|primary|secondary|tertiary|unclassified|living_street)$"]
          (around:${radiusM}, ${lat}, ${lon});
      );
      out geom;
    `.trim();

    const body = new URLSearchParams({ data: query }).toString();
    const response = await fetch(OVERPASS_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body,
    });
    if (!response.ok) {
      throw new Error(`Overpass HTTP ${response.status}: ${response.statusText}`);
    }
    const json = await response.json() as { elements?: any[] };
    if (!Array.isArray(json.elements)) return [];

    return json.elements
      .filter((el) => el.type === 'way' && Array.isArray(el.geometry) && el.geometry.length >= 2)
      .map((el) => ({
        id: Number(el.id),
        geometry: el.geometry.map((p: any) => ({ lat: Number(p.lat), lon: Number(p.lon) })),
        tags: el.tags ?? {},
      }));
  }
}
