import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/space_details/domain/models/space_details_model.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/space_details/domain/params/load_spaces_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/space_details/domain/services/space_details_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';

class RemoteSpaceDetailsService implements SpaceDetailsService {
  final HTTPService _httpService;

  RemoteSpaceDetailsService({
    required HTTPService httpService,
  }) : _httpService = httpService;

  static const _defaultErrorMessage = 'Failed to load space details';

  @override
  Future<SpaceDetailsModel> getSpaceDetails(LoadSpacesParam param) async {
    try {
      final response = await _httpService.get(
        path: 'endpoint',
        expectedResponseModel: (data) {
          return SpaceDetailsModel.fromJson(data as Map<String, dynamic>);
        },
      );
      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);
    }
  }
}
