import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/analytics/models/device_location_info.dart';
import 'package:syncrow_web/pages/analytics/params/get_device_location_data_param.dart';
import 'package:syncrow_web/pages/analytics/services/device_location/device_location_service.dart';
import 'package:syncrow_web/services/api/http_service.dart';

class RemoteDeviceLocationService implements DeviceLocationService {
  const RemoteDeviceLocationService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to load device location';

  @override
  Future<DeviceLocationInfo> get(GetDeviceLocationDataParam param) async {
    try {
      final response = await _httpService.get(
        path: '/weather',
        queryParameters: param.toJson(),
        expectedResponseModel: (data) {
          final response = data as Map<String, dynamic>;
          final location = response['data'] as Map<String, dynamic>;

          return DeviceLocationInfo.fromJson(location);
        },
      );
      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? ?? '';
      throw Exception(errorMessage);
    } catch (e) {
      throw Exception('$_defaultErrorMessage: $e');
    }
  }
}
