import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

import '../../../../constants/api_urls.dart';

/// The news repository
class NewsRepository {
  /// The Dio instance
  final Dio _dio = Dio(
    BaseOptions(
      baseUrl: TagesschauApiUrls.main,
      responseType: ResponseType.json,
    ),
  );

  /// Fetch the news
  Future<String> fetchNews() async {
    try {
      final Response<String> response = await _dio.get('/news');
      if (response.statusCode == 200) {
        if (response.data != null) {
          return response.data!;
        } else {
          throw Exception('Failed to fetch news: response data is null');
        }
      }
      throw Exception(
          'Failed to fetch news. Status code: ${response.statusCode}.');
    } catch (e) {
      debugPrint("Error fetching news: $e");
      rethrow;
    }
  }

  /// Fetch the next page of news
  fetchNewsPage(String url) async {
    final date = _extractDate(url);
    final Response<String> response =
        await _dio.get('/news', queryParameters: {'date': date});
    return response.data;
  }

  /// private method to extract the date from the url
  String _extractDate(String url) {
    final uri = Uri.parse(url);
    final queryParameters = uri.queryParameters;
    return queryParameters['date']!;
  }
}
