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/communities/domain/params/load_communities_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/domain/services/communities_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';
import 'package:syncrow_web/utils/constants/api_const.dart';

class RemoteCommunitiesService implements CommunitiesService {
  const RemoteCommunitiesService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to load communities';

  @override
  Future<CommunitiesPaginationModel> getCommunity(
    LoadCommunitiesParam param,
  ) async {
    try {
      final response = await _httpService.get(
        path: await _makeUrl(),
        queryParameters: {
          'page': param.page,
          'size': param.size,
          'includeSpaces': param.includeSpaces,
          if (param.search.isNotEmpty && param.search != 'null')
            'search': param.search,
        },
        expectedResponseModel: (json) => CommunitiesPaginationModel.fromJson(
          json as Map<String, dynamic>,
          CommunityModel.fromJsonList,
        ),
      );

      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 APIException(errorMessage);
    } catch (e) {
      final formattedErrorMessage = [_defaultErrorMessage, '$e'].join(': ');
      throw APIException(formattedErrorMessage);
    }
  }

  Future<String> _makeUrl() async {
    final projectUuid = await ProjectManager.getProjectUUID();
    if (projectUuid == null) throw APIException('Project UUID is required');
    return ApiEndpoints.getCommunityListv2.replaceAll(
      '{projectId}',
      projectUuid,
    );
  }
}
