import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/analytics/models/occupacy.dart';
import 'package:syncrow_web/pages/analytics/params/get_occupancy_param.dart';
import 'package:syncrow_web/pages/analytics/services/occupacy/occupacy_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';

final class RemoteOccupancyService implements OccupacyService {
  const RemoteOccupancyService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to load occupancy';

  @override
  Future<List<Occupacy>> load(GetOccupancyParam param) async {
    try {
      final response = await _httpService.get(
        path: '/occupancy/duration/space/${param.spaceUuid}',
        showServerMessage: true,
        queryParameters: param.toJson(),
        expectedResponseModel: (data) {
          final json = data as Map<String, dynamic>? ?? {};
          final mappedData = json['data'] as List<dynamic>? ?? [];
          return mappedData.map((e) {
            final jsonData = e as Map<String, dynamic>;
            return Occupacy.fromJson(jsonData);
          }).toList();
        },
      );
      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);
    }
  }
}
