import 'package:syncrow_web/pages/analytics/models/energy_data_model.dart';
import 'package:syncrow_web/pages/analytics/params/get_total_energy_consumption_param.dart';
import 'package:syncrow_web/pages/analytics/services/total_energy_consumption/total_energy_consumption_service.dart';
import 'package:syncrow_web/services/api/http_service.dart';

class RemoteTotalEnergyConsumptionService implements TotalEnergyConsumptionService {
  const RemoteTotalEnergyConsumptionService(this._httpService);

  final HTTPService _httpService;

  @override
  Future<List<EnergyDataModel>> load(
    GetTotalEnergyConsumptionParam param,
  ) async {
    try {
      final response = await _httpService.get(
        path: '/power-clamp/historical',
        showServerMessage: true,
        queryParameters: param.toJson(),
        expectedResponseModel: _TotalEnergyConsumptionResponseMapper.map,
      );

      return response;
    } catch (e) {
      throw Exception('Failed to load total energy consumption: $e');
    }
  }
}

abstract final class _TotalEnergyConsumptionResponseMapper {
  const _TotalEnergyConsumptionResponseMapper._();

  static List<EnergyDataModel> map(dynamic data) {
    final json = data as Map<String, dynamic>? ?? {};
    final dailyData = json['data'] as List<dynamic>? ?? [];

    return dailyData.map((dayData) {
      final date = dayData['date'] as String;
      final energyValue = double.tryParse(
            dayData['total_energy_consumed_kw'] as String? ?? '0',
          ) ??
          0.0;

      return EnergyDataModel(
        date: DateTime.parse(date),
        value: energyValue,
      );
    }).toList();
  }
}
