import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/domain/models/community_model.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/update_community/domain/params/update_community_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/update_community/domain/services/update_community_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';

class RemoteUpdateCommunityService implements UpdateCommunityService {
  const RemoteUpdateCommunityService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to update community';

  @override
  Future<CommunityModel> updateCommunity(UpdateCommunityParam param) async {
    try {
      final response = await _httpService.put(
        path: 'endpoint',
        expectedResponseModel: (data) => CommunityModel.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);
    }
  }
}
