import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/domain/models/bookable_space_model.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/domain/params/bookable_spaces_params.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/domain/service/bookable_spaces_service.dart';
import 'package:syncrow_web/pages/space_management_v2/main_module/shared/models/paginated_data_model.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 RemoteBookableSpacesService implements BookableSpacesService {
  final HTTPService _httpService;
  RemoteBookableSpacesService(this._httpService);
  static const _defaultErrorMessage = 'Failed to load Bookable Spaces';
  @override
  Future<PaginatedDataModel<BookableSpacemodel>> load(
      BookableSpacesParams param) async {
    try {
      final response = await _httpService.get(
        path: ApiEndpoints.bookableSpaces,
        queryParameters: {
          'configured': true,
          'page': param.currentPage,
        },
        expectedResponseModel: (json) {
          final result = json as Map<String, dynamic>;
          return PaginatedDataModel.fromJson(
            result,
            BookableSpacemodel.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? ?? '';
      final formattedErrorMessage = [
        _defaultErrorMessage,
        errorMessage,
      ].join(': ');
      throw APIException(formattedErrorMessage);
    } catch (e) {
      final formattedErrorMessage = [_defaultErrorMessage, '$e'].join(': ');
      throw APIException(formattedErrorMessage);
    }
  }
}
