from django.conf import settings
import requests


SUMUP_CLIENT_ID = settings.SUMUP_CLIENT_ID
SUMUP_CLIENT_SECRET = settings.SUMUP_CLIENT_SECRET
SUMUP_EMAIL = settings.SUMUP_MERCHANT_EMAIL

API_BASE = "https://api.sumup.com"


def obtener_token():
    """Obtiene un access token de SumUp (client_credentials)."""
    url = f"{API_BASE}/token"
    data = {
        "grant_type": "client_credentials",
        "client_id": SUMUP_CLIENT_ID,
        "client_secret": SUMUP_CLIENT_SECRET,
    }
    headers = {"Content-Type": "application/x-www-form-urlencoded"}

    response = requests.post(url, headers=headers, data=data, timeout=15)
    if response.status_code == 200:
        return response.json().get("access_token")
    raise Exception(f"Error al obtener token: {response.text}")


def crear_checkout_battlepay(reference, monto, descripcion, moneda="EUR", return_url=None):
    """
    Crea un checkout de SumUp para una orden Battlepay concreta.

    ``reference`` es la referencia única de la orden (battlepay_orders.reference);
    se usa como ``checkout_reference`` para poder mapear el webhook a la orden.
    Devuelve el JSON del checkout (incluye ``id``).
    """
    access_token = obtener_token()
    url = f"{API_BASE}/v0.1/checkouts"
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json",
    }
    data = {
        "checkout_reference": reference,
        "amount": float(monto),
        "currency": moneda,
        "pay_to_email": SUMUP_EMAIL,
        "description": descripcion,
    }
    if return_url:
        data["return_url"] = return_url

    response = requests.post(url, headers=headers, json=data, timeout=15)
    if response.status_code == 201:
        return response.json()
    raise Exception(f"Error al crear checkout: {response.text}")


def obtener_checkout(checkout_id):
    """Consulta un checkout por id. Devuelve su JSON (status, checkout_reference...)."""
    access_token = obtener_token()
    url = f"{API_BASE}/v0.1/checkouts/{checkout_id}"
    headers = {"Authorization": f"Bearer {access_token}"}
    response = requests.get(url, headers=headers, timeout=15)
    if response.status_code == 200:
        return response.json()
    raise Exception(f"Error al consultar checkout: {response.text}")


def crear_checkout(monto, moneda="EUR"):
    """Compatibilidad: checkout genérico de prueba. Devuelve el checkout_id."""
    checkout = crear_checkout_battlepay("pedido-prueba", monto, "Pago de prueba", moneda)
    return checkout.get("id")
