# Ubicación: src/App/api/business_central_routes.py

from flask import Blueprint, jsonify, request
# Asegúrate de que el nombre del import coincida con el nombre de tu archivo de servicio
from App.api.services.business_central_Service import BusinessCentralService

# --- Define el Blueprint para las rutas de Business Central ---
business_central_router = Blueprint('business_central', __name__)

# --- Instancia el servicio que manejará la lógica ---
service = BusinessCentralService()

# --- Rutas para Clientes (customerImports) ---

@business_central_router.route("/customers", methods=["GET"])
def get_customers():
    """Obtiene una lista de todos los clientes."""
    try:
        customers = service.get_customers()
        return jsonify(customers), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@business_central_router.route("/customers", methods=["POST"])
def create_customer():
    """Crea un nuevo cliente."""
    try:
        if not request.is_json:
            return jsonify({"error": "La solicitud debe ser de tipo JSON"}), 400
        data = request.get_json()
        new_customer = service.create_customer(data)
        return jsonify(new_customer), 201
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@business_central_router.route("/customers/<int:customer_id>", methods=["PATCH"])
def modify_customer(customer_id):
    """Modifica un cliente existente."""
    try:
        if not request.is_json:
            return jsonify({"error": "La solicitud debe ser de tipo JSON"}), 400
        data = request.get_json()
        updated_customer = service.modify_customer(customer_id, data)
        return jsonify(updated_customer), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@business_central_router.route("/customers/<int:customer_id>", methods=["DELETE"])
def delete_customer(customer_id):
    """Elimina un cliente."""
    try:
        service.delete_customer(customer_id)
        return '', 204 # Respuesta estándar para DELETE exitoso es no devolver contenido
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# --- Rutas para Items ---

@business_central_router.route("/items", methods=["GET"])
def get_items():
    """Obtiene una lista de todos los ítems."""
    try:
        items = service.get_items()
        return jsonify(items), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@business_central_router.route("/items", methods=["POST"])
def create_item():
    """Crea un nuevo ítem."""
    try:
        if not request.is_json:
            return jsonify({"error": "La solicitud debe ser de tipo JSON"}), 400
        data = request.get_json()
        new_item = service.create_item(data)
        return jsonify(new_item), 201
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# --- Rutas para Contactos --- (AÑADIDO)

@business_central_router.route("/contacts", methods=["GET"])
def get_contacts():
    """Obtiene una lista de todos los contactos."""
    try:
        contacts = service.get_contacts()
        return jsonify(contacts), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# --- Rutas para Vendedores (Salespersons) --- (AÑADIDO)

@business_central_router.route("/salespersons", methods=["GET"])
def get_salespersons():
    """Obtiene una lista de todos los vendedores."""
    try:
        salespersons = service.get_salespersons()
        return jsonify(salespersons), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# --- Rutas para Cotizaciones (Quotes) ---

@business_central_router.route("/quotes", methods=["GET"])
def get_quote_lines():
    """Obtiene las líneas de cotización."""
    try:
        quotes = service.get_quote_lines()
        return jsonify(quotes), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500
        
@business_central_router.route("/quotes", methods=["POST"])
def create_quote():
    """Crea una nueva cotización."""
    try:
        if not request.is_json:
            return jsonify({"error": "La solicitud debe ser de tipo JSON"}), 400
        data = request.get_json()
        new_quote = service.create_quote(data)
        return jsonify(new_quote), 201
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@business_central_router.route("/quotes/<system_id>/<quote_no>/<int:line_no>", methods=["DELETE"])
def delete_quote_line(system_id, quote_no, line_no):
    """Elimina una línea de cotización específica."""
    try:
        service.delete_quote_line(system_id, quote_no, line_no)
        return '', 204
    except Exception as e:
        return jsonify({"error": str(e)}), 500
        
# --- Rutas para Contactos Buffer (Webintegration) ---

@business_central_router.route("/contacts-buffer", methods=["GET"])
def get_contact_buffer():
    """Obtiene los contactos del buffer."""
    try:
        contacts = service.get_contact_buffer()
        return jsonify(contacts), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500
        
@business_central_router.route("/contacts-buffer", methods=["POST"])
def create_contact_buffer():
    """Crea un nuevo contacto en el buffer."""
    try:
        if not request.is_json:
            return jsonify({"error": "La solicitud debe ser de tipo JSON"}), 400
        data = request.get_json()
        new_contact = service.create_contact_buffer(data)
        return jsonify(new_contact), 201
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# --- Rutas para Oportunidades --- (AÑADIDO)

@business_central_router.route("/opportunities", methods=["GET"])
def get_opportunities():
    """Obtiene una lista de todas las oportunidades."""
    try:
        opportunities = service.get_opportunities()
        return jsonify(opportunities), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500