import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/analytics/models/occupancy_heat_map_model.dart';
import 'package:syncrow_web/pages/analytics/params/get_occupancy_heat_map_param.dart';
import 'package:syncrow_web/pages/analytics/services/occupancy_heat_map/occupancy_heat_map_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';

final class RemoteOccupancyHeatMapService implements OccupancyHeatMapService {
  const RemoteOccupancyHeatMapService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to load occupancy heat map';

  @override
  Future<List<OccupancyHeatMapModel>> load(GetOccupancyHeatMapParam param) async {
    try {
      final response = await _httpService.get(
        path: '/occupancy/heat-map/space/${param.spaceUuid}',
        showServerMessage: true,
        queryParameters: param.toJson(),
        expectedResponseModel: (response) {
          final json = response as Map<String, dynamic>;
          final dailyData = json['data'] as List<dynamic>? ?? <dynamic>[];

          final result = dailyData.map(
            (json) => OccupancyHeatMapModel.fromJson(json as Map<String, dynamic>),
          );

          return result.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);
    }
  }
}
