import '../../../core/api/api_client.dart';
import '../../../core/api/api_paths.dart';
import '../domain/inventory_item.dart';
import '../domain/inventory_consumption.dart';

class InventoryRepository {
  final ApiClient _api;

  const InventoryRepository(this._api);

  Future<List<InventoryItem>> fetchInventory({
    String? location,
    String? sort,
    String? token,
  }) async {
    final params = <String, String>{};
    if (location != null && location.isNotEmpty) params['location'] = location;
    if (sort != null && sort.isNotEmpty) params['sort'] = sort;

    final query = params.isEmpty
        ? ''
        : '?${params.entries.map((e) => '${e.key}=${Uri.encodeComponent(e.value)}').join('&')}';

    final data = await _api.getJson('${InventoryApiPaths.list}$query', token: token);
    final list = data as List<dynamic>;
    return list.map((e) => InventoryItem.fromJson(e as Map<String, dynamic>)).toList();
  }

  Future<InventoryItem> fetchInventoryItem(int id, {String? token}) async {
    final items = await fetchInventory(token: token);
    return items.firstWhere((item) => item.id == id);
  }

  Future<InventoryItem> createInventoryItem(
    Map<String, dynamic> body, {
    String? token,
  }) async {
    final data = await _api.postJson(InventoryApiPaths.list, body: body, token: token);
    return InventoryItem.fromJson(data as Map<String, dynamic>);
  }

  Future<InventoryItem> updateInventoryItem(
    int id,
    Map<String, dynamic> body, {
    String? token,
  }) async {
    final data = await _api.patchJson(InventoryApiPaths.update(id), body: body, token: token);
    return InventoryItem.fromJson(data as Map<String, dynamic>);
  }

  Future<void> deleteInventoryItem(int id, {String? token}) async {
    await _api.deleteJson(InventoryApiPaths.remove(id), token: token);
  }

  Future<InventoryItem> consumeInventoryItem(
    int id, {
    required double amountUsed,
    String? comment,
    String? token,
  }) async {
    final body = <String, dynamic>{'amountUsed': amountUsed};
    if (comment != null && comment.isNotEmpty) body['comment'] = comment;
    final data = await _api.postJson(InventoryApiPaths.consume(id), body: body, token: token);
    return InventoryItem.fromJson(data as Map<String, dynamic>);
  }

  Future<List<InventoryConsumption>> fetchConsumptionHistory(
    int id, {
    String? token,
  }) async {
    final data = await _api.getJson(InventoryApiPaths.consumptionHistory(id), token: token);
    final list = data as List<dynamic>;
    return list
        .map((e) => InventoryConsumption.fromJson(e as Map<String, dynamic>))
        .toList();
  }
}
