# app.py for order-service-py

from flask import Flask, jsonify
import requests

app = Flask(__name__)

# In a real application, this would interact with a database
orders = [
    {"id": "ord1", "user_id": "1", "product_id": "101", "quantity": 1, "status": "Pending"},
    {"id": "ord2", "user_id": "2", "product_id": "102", "quantity": 2, "status": "Completed"}
]

@app.route('/orders', methods=['GET'])
def get_all_orders():
    """Returns a list of all orders."""
    return jsonify(orders)

@app.route('/orders/<string:order_id>', methods=['GET'])
def get_order_by_id(order_id):
    """Returns a single order by ID."""
    for order in orders:
        if order['id'] == order_id:
            return jsonify(order)
    return jsonify({"message": "Order not found"}), 404

@app.route('/orders/create/<string:user_id>/<string:product_id>/<int:quantity>', methods=['GET'])
def create_order(user_id, product_id, quantity):
    """Creates a dummy order and demonstrates service-to-service communication."""
    response_messages = []

    # --- Service-to-Service Communication Example ---
    # This demonstrates how order-service-py communicates with user-service-py and product-service-py.
    # In a Kubernetes environment, service discovery is handled by Kubernetes DNS.
    # You can use the service name directly as the hostname (e.g., http://user-service-py:8080).

    # Call User Service to get user details
    # The hostname 'user-service-py' resolves to the ClusterIP of the user-service-py Kubernetes Service.
    # The port '8080' is the targetPort defined in the user-service-py Kubernetes Service.
    try:
        user_service_url = f"http://user-service-py:8080/users/{user_id}"
        user_response = requests.get(user_service_url)
        user_data = user_response.json()
        response_messages.append(f"User Service Response: {user_data}")
    except requests.exceptions.ConnectionError as e:
        response_messages.append(f"Error connecting to User Service: {e}")
        user_data = None

    # Call Product Service to get product details
    # The hostname 'product-service-py' resolves to the ClusterIP of the product-service-py Kubernetes Service.
    # The port '8081' is the targetPort defined in the product-service-py Kubernetes Service.
    try:
        product_service_url = f"http://product-service-py:8081/products/{product_id}"
        product_response = requests.get(product_service_url)
        product_data = product_response.json()
        response_messages.append(f"Product Service Response: {product_data}")
    except requests.exceptions.ConnectionError as e:
        response_messages.append(f"Error connecting to Product Service: {e}")
        product_data = None

    if user_data and product_data:
        # In a real scenario, you would create the order here
        new_order = {
            "id": f"ord{len(orders) + 1}",
            "user_id": user_id,
            "product_id": product_id,
            "quantity": quantity,
            "status": "Created"
        }
        orders.append(new_order)
        response_messages.append(f"Order created: {new_order}")
    else:
        response_messages.append("Order creation failed due to upstream service errors.")

    return jsonify({"status": "Attempting to create order", "details": response_messages})

if __name__ == '__main__':
    # Run the Flask app on port 8082
    app.run(host='0.0.0.0', port=8082)
