fetchCountries method

Future<List<LokotroCountry>> fetchCountries({
  1. bool forceRefresh = false,
})

Fetch available countries from API

Implementation

Future<List<LokotroCountry>> fetchCountries({bool forceRefresh = false}) async {
  // Return cached data if valid and not forcing refresh
  if (!forceRefresh && _isCacheValid && _cachedCountries != null) {
    if (kDebugMode) {
      debugPrint('[Lokotro Country Service] Returning cached countries: ${_cachedCountries!.length}');
    }
    return _cachedCountries!;
  }

  try {
    if (kDebugMode) {
      debugPrint('[Lokotro Country Service] Fetching countries from API...');
    }

    final httpClient = LokotroHttpClient.instance;
    final response = await httpClient.get<Map<String, dynamic>>(
      '/payments/countries/fetch/countries-available',
      parser: (data) => data as Map<String, dynamic>,
    );

    if (response.isSuccess && response.data != null) {
      final countriesResponse = LokotroCountriesResponse.fromJson(response.data!);

      if (countriesResponse.isSuccess) {
        _cachedCountries = countriesResponse.countries;
        _lastFetchTime = DateTime.now();

        if (kDebugMode) {
          debugPrint('[Lokotro Country Service] Fetched ${_cachedCountries!.length} countries');
          for (final country in _cachedCountries!) {
            debugPrint('[Lokotro Country Service] - ${country.flag} ${country.name} (+${country.primaryCountryCode}): ${country.validPrefixes.length} prefixes');
          }
        }

        return _cachedCountries!;
      } else {
        throw Exception(countriesResponse.message);
      }
    } else {
      throw Exception(response.message);
    }
  } catch (e) {
    if (kDebugMode) {
      debugPrint('[Lokotro Country Service] Error fetching countries: $e');
    }

    // Return cached data if available, even if expired
    if (_cachedCountries != null) {
      if (kDebugMode) {
        debugPrint('[Lokotro Country Service] Returning stale cache due to error');
      }
      return _cachedCountries!;
    }

    // Return empty list if no cache and API failed
    return [];
  }
}