import requests
import uuid
import asyncio
from config import QRIS_CREATE_URL, QRIS_CHECK_URL


def create_qris_payment(amount: int, order_id: str = None, product_name: str = "VPS Order", customer_name: str = "Client", customer_id: str = "client") -> dict:
    if not order_id:
        order_id = str(uuid.uuid4())[:8].upper()

    payload = {
        "customer_name": customer_name,
        "customer_email": f"{customer_id}@pentahostinger.id",
        "customer_phone": "081233242006",
        "product_name": product_name,
        "product_price": amount,
        "quantity": 1,
        "acquirer": "gopay"
    }

    try:
        response = requests.post(QRIS_CREATE_URL, json=payload, timeout=15)
        result = response.json()
        result["order_id"] = result.get("order_id", order_id)
        return result
    except Exception as e:
        return {"status": "error", "message": str(e), "order_id": order_id}


def check_qris_payment(order_id: str) -> dict:
    try:
        response = requests.get(QRIS_CHECK_URL, params={"order_id": order_id}, timeout=15)
        return response.json()
    except Exception as e:
        return {"status": "error", "message": str(e)}


async def poll_qris_status(order_id: str, callback, interval: int = 5, timeout: int = 300):
    elapsed = 0
    while elapsed < timeout:
        await asyncio.sleep(interval)
        elapsed += interval
        result = check_qris_payment(order_id)
        order_data = result.get("order_data", {})
        status = order_data.get("transaction_status", "") or result.get("status", "")
        if status in ("settlement", "capture", "paid", "success"):
            await callback("success", result)
            return
        elif status in ("deny", "cancel", "expire", "failed"):
            await callback("failed", result)
            return
    await callback("timeout", {})