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/update_space/domain/services/update_space_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';

class RemoteUpdateSpaceService implements UpdateSpaceService {
  const RemoteUpdateSpaceService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to update space';

  @override
  Future<SpaceDetailsModel> updateSpace(SpaceDetailsModel space) async {
    try {
      final response = await _httpService.put(
        path: 'endpoint',
        body: space.toJson(),
        expectedResponseModel: (data) => 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);
    }
  }
}
