import '../models/service_info.dart';
import '../data/legacy_service_data.dart';
import 'url_matcher_service.dart';
import 'category_mapper_service.dart';

/// SMS에서 서비스 정보를 추출하는 서비스 클래스
class SmsExtractorService {
  final UrlMatcherService _urlMatcher;
  final CategoryMapperService _categoryMapper;

  SmsExtractorService(this._urlMatcher, this._categoryMapper);

  /// SMS에서 URL과 서비스 정보 추출
  Future<ServiceInfo?> extractServiceFromSms(String smsText) async {
    // URL 패턴 찾기
    final urlPattern = RegExp(
      r'https?://(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)',
      caseSensitive: false,
    );

    final matches = urlPattern.allMatches(smsText);

    for (final match in matches) {
      final url = match.group(0);
      if (url != null) {
        final serviceInfo = await _urlMatcher.findServiceByUrl(url);
        if (serviceInfo != null) {
          return serviceInfo;
        }
      }
    }

    // URL로 못 찾았으면 서비스명으로 시도
    final lowerSms = smsText.toLowerCase();

    // 모든 서비스명 검사
    for (final entry in LegacyServiceData.allServices.entries) {
      if (lowerSms.contains(entry.key.toLowerCase())) {
        final categoryId =
            await _categoryMapper.findCategoryByServiceName(entry.key) ??
                'other';

        return ServiceInfo(
          serviceId: entry.key,
          serviceName: entry.key,
          serviceUrl: entry.value,
          cancellationUrl: null,
          categoryId: categoryId,
          categoryNameKr: '',
          categoryNameEn: '',
        );
      }
    }

    return null;
  }
}
