import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/analytics/services/power_clamp_info/power_clamp_info_service.dart';
import 'package:syncrow_web/pages/device_managment/power_clamp/models/power_clamp_model.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';

final class RemotePowerClampInfoService implements PowerClampInfoService {
  const RemotePowerClampInfoService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to fetch power clamp info';

  @override
  Future<PowerClampModel> getInfo(String deviceId) async {
    try {
      final response = await _httpService.get(
        path: '/devices/$deviceId/functions/status',
        showServerMessage: true,
        expectedResponseModel: (data) {
          final json = data as Map<String, Object?>? ?? {};
          final mappedData = json['data'] as Map<String, Object?>? ?? {};
          return PowerClampModel.fromJson(mappedData);
        },
      );
      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);
    }
  }
}
