import '../models/inventory_models.dart';
import 'inventory_repository.dart';

class InventoryService {
  InventoryService({InventoryRepository? repository}) : _repository = repository ?? InventoryRepository();

  final InventoryRepository _repository;

  Future<List<InventorySummary>> fetchSummaries({bool includeHidden = false}) {
    return _repository.fetchSummaries(includeHidden: includeHidden);
  }

  Future<List<InventoryMovement>> fetchMovements(String productId, {int limit = 50}) {
    return _repository.fetchMovements(productId, limit: limit);
  }

  Future<InventorySummary> recordManualMovement({
    required String productId,
    required InventoryMovementType type,
    required int quantity,
    String? reference,
    String? notes,
  }) {
    if (quantity == 0 && type != InventoryMovementType.adjustment) {
      throw ArgumentError('quantity must be non-zero');
    }
    final normalizedQuantity = quantity.abs();
    final delta = _calculateDelta(type, quantity);
    final recordedQuantity = type == InventoryMovementType.adjustment ? normalizedQuantity : normalizedQuantity;

    return _repository.recordMovement(
      productId: productId,
      type: type,
      quantity: recordedQuantity,
      quantityDelta: delta,
      reference: reference,
      notes: notes,
    );
  }

  int _calculateDelta(InventoryMovementType type, int quantity) {
    switch (type) {
      case InventoryMovementType.receipt:
        return quantity.abs();
      case InventoryMovementType.issue:
        return -quantity.abs();
      case InventoryMovementType.adjustment:
        return quantity;
    }
  }
}
