import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/analytics/models/phases_energy_consumption.dart';
import 'package:syncrow_web/pages/analytics/params/get_energy_consumption_by_phases_param.dart';
import 'package:syncrow_web/pages/analytics/services/energy_consumption_by_phases/energy_consumption_by_phases_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';

final class RemoteEnergyConsumptionByPhasesService
    implements EnergyConsumptionByPhasesService {
  const RemoteEnergyConsumptionByPhasesService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to load energy consumption per phase';

  @override
  Future<List<PhasesEnergyConsumption>> load(
    GetEnergyConsumptionByPhasesParam param,
  ) async {
    try {
      final response = await _httpService.get(
        path: '/power-clamp/${param.powerClampUuid}/historical',
        showServerMessage: true,
        queryParameters: param.toJson(),
        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 PhasesEnergyConsumption.fromJson(jsonData);
          }).toList();
        },
      );
      return response;
    } on DioException catch (e) {
      final message = e.response?.data as Map<String, dynamic>?;
      final error = message?['error'] as Map<String, dynamic>?;
      final errorMessage = error?['error'] as String? ?? '';
      final formattedErrorMessage = [_defaultErrorMessage, errorMessage].join(': ');
      throw APIException(formattedErrorMessage);
    } catch (e) {
      final formattedErrorMessage = [_defaultErrorMessage, '$e'].join(': ');
      throw APIException(formattedErrorMessage);
    }
  }
}
