import 'package:logging/logging.dart';
import '../../../core/api/api_client.dart';
import '../../../core/api/api_paths.dart';
import '../domain/pantry_item.dart';
import '../domain/pantry_product.dart';

final _logger = Logger('PantryRepository');

class PantryRepository {
  final ApiClient _api;

  const PantryRepository(this._api);

  Future<List<PantryItem>> fetchPantry({String? token}) async {
    try {
      final data = await _api.getJson(PantryApiPaths.list, token: token);
      final list = data as List<dynamic>;
      _logger.info('Fetched ${list.length} pantry items');
      return list
          .map((e) => PantryItem.fromJson(e as Map<String, dynamic>))
          .toList();
    } catch (error) {
      _logger.severe('Failed to fetch pantry items: $error');
      rethrow;
    }
  }

  Future<List<PantryProduct>> fetchProducts({String? token}) async {
    try {
      final data = await _api.getJson(ProductApiPaths.list, token: token);
      final list = data as List<dynamic>;
      _logger.info('Fetched ${list.length} products');
      return list
          .map((e) => PantryProduct.fromJson(e as Map<String, dynamic>))
          .toList();
    } catch (error) {
      _logger.severe('Failed to fetch products: $error');
      rethrow;
    }
  }

  Future<PantryItem> createPantryItem(int productId, {String? token}) async {
    try {
      final data = await _api.postJson(
        PantryApiPaths.list,
        body: {'productId': productId},
        token: token,
      );
      _logger.info('Created pantry item for product ID: $productId');
      return PantryItem.fromJson(data as Map<String, dynamic>);
    } catch (error) {
      _logger.severe('Failed to create pantry item: $error');
      rethrow;
    }
  }

  Future<void> deletePantryItem(int id, {String? token}) async {
    try {
      await _api.deleteJson(PantryApiPaths.remove(id), token: token);
      _logger.info('Deleted pantry item with ID: $id');
    } catch (error) {
      _logger.severe('Failed to delete pantry item: $error');
      rethrow;
    }
  }
}