import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/analytics/models/analytics_device.dart';
import 'package:syncrow_web/pages/analytics/params/get_analytics_devices_param.dart';
import 'package:syncrow_web/pages/analytics/services/analytics_devices/analytics_devices_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';

final class RemoteEnergyManagementAnalyticsDevicesService
    implements AnalyticsDevicesService {
  const RemoteEnergyManagementAnalyticsDevicesService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to load analytics devices';

  @override
  Future<List<AnalyticsDevice>> getDevices(GetAnalyticsDevicesParam param) async {
    try {
      final response = await _httpService.get(
        path: '/devices-space-community/recursive-child',
        queryParameters: param.toJson()
          ..addAll({'productType': param.deviceTypes.first}),
        expectedResponseModel: (response) {
          final json = response as Map<String, dynamic>;
          final dailyData = json['data'] as List<dynamic>? ?? <dynamic>[];

          final result = dailyData.map(
            (json) => AnalyticsDevice.fromJson(json as Map<String, dynamic>),
          );

          return result.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) {
      throw APIException('$_defaultErrorMessage: $e');
    }
  }
}
