import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.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/create_community/domain/param/create_community_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/create_community/domain/services/create_community_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';

class RemoteCreateCommunityService implements CreateCommunityService {
  const RemoteCreateCommunityService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to create community';

  @override
  Future<CommunityModel> createCommunity(CreateCommunityParam param) async {
    try {
      final response = await _httpService.post(
        path: await _makeUrl(),
        body: {
          'name': param.name,
          'description': param.description,
        },
        expectedResponseModel: (data) {
          final json = data as Map<String, dynamic>;
          if (json['success'] == true) {
            return CommunityModel.fromJson(
              json['data'] as Map<String, dynamic>,
            );
          }
          return null;
        },
      );

      if (response == null) {
        throw APIException(
          _getErrorMessageFromBody(response as Map<String, dynamic>?),
        );
      }
      return response;
    } on DioException catch (e) {
      final message = e.response?.data as Map<String, dynamic>?;
      throw APIException(_getErrorMessageFromBody(message));
    } catch (e) {
      final formattedErrorMessage = [_defaultErrorMessage, '$e'].join(': ');
      throw APIException(formattedErrorMessage);
    }
  }

  String _getErrorMessageFromBody(Map<String, dynamic>? body) {
    if (body == null) {
      return _defaultErrorMessage;
    }
    final error = body['error'] as Map<String, dynamic>?;
    final errorMessage = error?['message'] as String? ?? '';
    return errorMessage;
  }

  Future<String> _makeUrl() async {
    final projectUuid = await ProjectManager.getProjectUUID();
    if (projectUuid == null) {
      throw APIException('Project UUID is not set');
    }
    return '/projects/$projectUuid/communities';
  }
}
