import 'dart:collection';

import 'package:lunchpick/domain/entities/restaurant.dart';

import '../../api/naver_api_client.dart';
import 'naver_map_parser.dart';

/// 네이버 지도 URL을 처리하고 결과를 캐시하는 경량 프로세서.
/// - 단축 URL 해석 → 지도 파서 실행
/// - 동일 URL 재요청 시 메모리 캐시 반환
class NaverUrlProcessor {
  final NaverApiClient _apiClient;
  final NaverMapParser _mapParser;
  final _cache = HashMap<String, Restaurant>();

  NaverUrlProcessor({NaverApiClient? apiClient, NaverMapParser? mapParser})
    : _apiClient = apiClient ?? NaverApiClient(),
      _mapParser = mapParser ?? NaverMapParser(apiClient: apiClient);

  Future<Restaurant> processUrl(
    String url, {
    double? userLatitude,
    double? userLongitude,
  }) async {
    final normalizedUrl = url.trim();
    if (_cache.containsKey(normalizedUrl)) {
      return _cache[normalizedUrl]!;
    }

    final resolved = await _apiClient.resolveShortUrl(normalizedUrl);
    final restaurant = await _mapParser.parseRestaurantFromUrl(
      resolved,
      userLatitude: userLatitude,
      userLongitude: userLongitude,
    );
    _cache[normalizedUrl] = restaurant;
    _cache[resolved] = restaurant;
    return restaurant;
  }

  void clearCache() => _cache.clear();
}
