import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/products/domain/models/product.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/products/domain/params/load_products_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/products/domain/services/products_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';

class RemoteProductsService implements ProductsService {
  const RemoteProductsService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to load devices';

  @override
  Future<List<Product>> getProducts(LoadProductsParam param) async {
    try {
      final response = await _httpService.get(
        path: 'devices',
        queryParameters: {
          'spaceUuid': param.spaceUuid,
          if (param.type != null) 'type': param.type,
          if (param.status != null) 'status': param.status,
        },
        expectedResponseModel: (data) {
          return (data as List)
              .map((e) => Product.fromJson(e as Map<String, dynamic>))
              .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);
    }
  }
}
