import 'package:syncrow_web/pages/analytics/models/air_quality_data_model.dart';
import 'package:syncrow_web/pages/analytics/params/get_air_quality_distribution_param.dart';
import 'package:syncrow_web/pages/analytics/services/air_quality_distribution/air_quality_distribution_service.dart';
import 'package:syncrow_web/services/api/http_service.dart';

final class RemoteAirQualityDistributionService
    implements AirQualityDistributionService {
  RemoteAirQualityDistributionService(this._httpService);

  final HTTPService _httpService;

  @override
  Future<List<AirQualityDataModel>> getAirQualityDistribution(
    GetAirQualityDistributionParam param,
  ) async {
    try {
      final response = await _httpService.get(
        path: '/aqi/distribution/space/${param.spaceUuid}',
        queryParameters: {
          'monthDate': _formatDate(param.date),
          'pollutantType': param.aqiType.code,
        },
        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 AirQualityDataModel.fromJson(jsonData);
          }).toList();
        },
      );
      return response;
    } catch (e) {
      throw Exception('Failed to load energy consumption per phase: $e');
    }
  }

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