# apps/aroflo_connector_app/api/v1/routes.py
from __future__ import annotations

from flask import request, jsonify, current_app

from .blueprint import bp
from ...services.dispatcher import get_zones_overview, dispatch_zone_query
from ...client import get_client  # TODO: ajusta a tu helper real


def _get_aroflo_client():
    """
    Wrapper centralizado por si luego usamos current_app.config, etc.
    """
    return get_client()


@bp.get("/zones")
def list_zones():
    client = _get_aroflo_client()
    data = get_zones_overview(client)
    return jsonify(data)


@bp.post("/zone/<zone_code>/query")
def post_zone_query(zone_code: str):
    client = _get_aroflo_client()
    payload = request.get_json(silent=True) or {}

    try:
        data = dispatch_zone_query(client, zone_code, payload)
        return jsonify(data)
    except KeyError as e:
        return jsonify({"error": str(e)}), 404
    except ValueError as e:
        return jsonify({"error": str(e)}), 400
    except Exception as e:
        current_app.logger.exception("Error en zone query")
        return jsonify({"error": "Internal error", "details": str(e)}), 500
