# inventory_service.py
import pika
import json

# RabbitMQ setup
RABBITMQ_HOST = 'localhost'
connection = pika.BlockingConnection(pika.ConnectionParameters(RABBITMQ_HOST))
channel = connection.channel()
channel.queue_declare(queue='rental_requests')

# Database simulation
inventory = {
    'perceuse': 5,
    'tondeuse': 3,
    'ponceuse': 4,
    'scie': 2
}

def process_rental(ch, method, properties, body):
    rental_data = json.loads(body)
    product = rental_data['product']
    quantity = rental_data['quantity']
    
    if product in inventory and inventory[product] >= quantity:
        inventory[product] -= quantity
        print(f"Déstockage effectué: {quantity} {product}(s)")
        print(f"Stock restant - {product}: {inventory[product]}")
    else:
        print(f"Erreur: Stock insuffisant pour {product}")

channel.basic_consume(
    queue='rental_requests',
    on_message_callback=process_rental,
    auto_ack=True
)

print("Service de gestion des stocks démarré. En attente de demandes...")
channel.start_consuming()
