/**
 * Phase 8.5d (2026-04-29) — Recherche du POI/business le plus proche par type.
 *
 * Utilisé pour :
 *   - Hospitalisation : déplacer le joueur au point GPS de l'hôpital le + proche
 *   - Jugement : déplacer le joueur au tribunal le + proche au passage en step 'jugement'
 *   - Achat hôpital : identifier l'hôpital où le joueur est hospitalisé
 *
 * Cache local 5min par (type, lat_round, lon_round) pour éviter re-query
 * sur les events fréquents (combat tick).
 */
import { AppDataSource } from '../config/database';
import { Business } from '../models/Business';
import { haversineDistance } from '../constants/travel-speeds';

const businessRepo = () => AppDataSource.getRepository(Business);

interface NearestPoiResult {
  id: string;
  name: string;
  type: string;
  lat: number;
  lon: number;
  distance_km: number;
}

interface CacheEntry {
  expires_at: number;
  result: NearestPoiResult | null;
}

const CACHE_TTL_MS = 5 * 60 * 1000;
const cache = new Map<string, CacheEntry>();

function cacheKey(type: string, lat: number, lon: number): string {
  // Round à 0.01° (~1.1km) pour matching cache plausible
  return `${type}:${lat.toFixed(2)}:${lon.toFixed(2)}`;
}

export class NearestPoiService {

  /**
   * Trouve le business le plus proche du type donné.
   * Cache 5min sur position arrondie à 0.01° (suffisant pour usage hôpital/tribunal).
   *
   * Returns null si aucun POI du type trouvé (DB vide ou type invalide).
   */
  static async findNearestByType(
    type: string,
    fromLat: number,
    fromLon: number,
  ): Promise<NearestPoiResult | null> {
    const key = cacheKey(type, fromLat, fromLon);
    const cached = cache.get(key);
    if (cached && cached.expires_at > Date.now()) {
      return cached.result;
    }

    // Query tous les business du type, calcul haversine en JS (acceptable
    // pour une centaine de POIs max). PostGIS pourrait optimiser plus tard.
    const candidates = await businessRepo()
      .createQueryBuilder('b')
      .where('b.type = :type', { type })
      .andWhere('b.location_lat IS NOT NULL AND b.location_lon IS NOT NULL')
      .getMany();

    if (candidates.length === 0) {
      cache.set(key, { expires_at: Date.now() + CACHE_TTL_MS, result: null });
      return null;
    }

    let best: NearestPoiResult | null = null;
    for (const b of candidates) {
      const lat = Number(b.location_lat);
      const lon = Number(b.location_lon);
      if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
      const distance = haversineDistance(fromLat, fromLon, lat, lon);
      if (best === null || distance < best.distance_km) {
        best = {
          id: b.id,
          name: b.name,
          type: b.type,
          lat,
          lon,
          distance_km: distance,
        };
      }
    }

    cache.set(key, { expires_at: Date.now() + CACHE_TTL_MS, result: best });
    return best;
  }

  /** Helper : hôpital le plus proche. */
  static async findNearestHospital(fromLat: number, fromLon: number): Promise<NearestPoiResult | null> {
    return NearestPoiService.findNearestByType('hospital', fromLat, fromLon);
  }

  /** Helper : tribunal le plus proche. */
  static async findNearestCourthouse(fromLat: number, fromLon: number): Promise<NearestPoiResult | null> {
    // Note : les tribunaux sont seedés en business_type='other' avec icon='courthouse'
    // dans le code actuel (cf seeds/tribunaux.seed.ts). On query par icon via la
    // table POI au lieu de business.type pour être robuste.
    const { POI } = await import('../models/POI');
    const poiRepo = AppDataSource.getRepository(POI);
    const candidates = await poiRepo
      .createQueryBuilder('p')
      .where('p.icon = :icon OR p.category = :cat', { icon: 'courthouse', cat: 'infrastructure_courthouse' })
      .getMany();

    if (candidates.length === 0) return null;

    let best: NearestPoiResult | null = null;
    for (const p of candidates) {
      const lat = Number(p.location_lat);
      const lon = Number(p.location_lon);
      if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
      const distance = haversineDistance(fromLat, fromLon, lat, lon);
      if (best === null || distance < best.distance_km) {
        best = {
          id: p.id,
          name: p.name || 'Tribunal',
          type: 'courthouse',
          lat,
          lon,
          distance_km: distance,
        };
      }
    }
    return best;
  }

  /** Helper : pharmacy la plus proche (achat carte santé). */
  static async findNearestPharmacy(fromLat: number, fromLon: number): Promise<NearestPoiResult | null> {
    return NearestPoiService.findNearestByType('pharmacy', fromLat, fromLon);
  }

  /** Vide le cache (tests, debug, ou forçage post-seed). */
  static clearCache(): void {
    cache.clear();
  }
}
