import 'package:syncrow_web/pages/analytics/models/range_of_aqi.dart';
import 'package:syncrow_web/pages/analytics/params/get_range_of_aqi_param.dart';
import 'package:syncrow_web/pages/analytics/services/range_of_aqi/range_of_aqi_service.dart';
import 'package:syncrow_web/services/api/http_service.dart';

final class RemoteRangeOfAqiService implements RangeOfAqiService {
  const RemoteRangeOfAqiService(this._httpService);

  final HTTPService _httpService;

  @override
  Future<List<RangeOfAqi>> load(GetRangeOfAqiParam param) async {
    try {
      final response = await _httpService.get(
        path: '/aqi/range/space/${param.spaceUuid}',
        queryParameters: {'monthDate': _formatDate(param.date)},
        expectedResponseModel: (data) {
          final json = data as Map<String, dynamic>? ?? {};
          final mappedData = json['data'] as List<dynamic>? ?? [];
          return mappedData.map((e) {
            final jsonData = e as Map<String, dynamic>;
            return RangeOfAqi.fromJson(jsonData);
          }).toList();
        },
      );
      return response;
    } catch (e) {
      throw Exception('Failed to load range of aqi: $e');
    }
  }

  static String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}';
  }
}
