import aiohttp
from core.config import config

NOWPAYMENTS_API_URL = "https://api.nowpayments.io/v1"


async def _get_api_key() -> str:
    """خواندن API Key از دیتابیس، اگر نبود از config."""
    try:
        from database.database import AsyncSessionLocal
        from database.crud import get_setting
        async with AsyncSessionLocal() as session:
            key = await get_setting(session, "nowpayments_api_key", "")
            if key:
                return key
    except Exception:
        pass
    return config.nowpayments_api_key


async def is_nowpayments_enabled() -> bool:
    """بررسی اینکه آیا پرداخت USDT فعال است."""
    try:
        from database.database import AsyncSessionLocal
        from database.crud import get_setting
        async with AsyncSessionLocal() as session:
            val = await get_setting(session, "nowpayments_enabled", "true")
            return val == "true"
    except Exception:
        return True


async def create_invoice(price_amount: float, order_id: str, order_description: str) -> dict:
    """ساخت یک فاکتور برای پرداخت تتری"""
    api_key = await _get_api_key()
    if not api_key:
        return {"status": False, "message": "API Key نوپیمنتز تنظیم نشده است."}

    headers = {
        "x-api-key": api_key,
        "Content-Type": "application/json"
    }
    payload = {
        "price_amount": price_amount,
        "price_currency": "usd",
        "pay_currency": "usdttrc20",
        "order_id": order_id,
        "order_description": order_description
    }

    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(
                f"{NOWPAYMENTS_API_URL}/invoice",
                json=payload,
                headers=headers,
                timeout=aiohttp.ClientTimeout(total=15)
            ) as response:
                if response.status == 200:
                    data = await response.json()
                    return {
                        "status": True,
                        "invoice_url": data.get("invoice_url"),
                        "payment_id": data.get("id")
                    }
                else:
                    return {"status": False, "message": await response.text()}
    except Exception as e:
        return {"status": False, "message": str(e)}


async def check_payment_status(payment_id: str) -> str:
    """بررسی وضعیت پرداخت فاکتور"""
    api_key = await _get_api_key()
    if not api_key:
        return "error"

    headers = {"x-api-key": api_key}
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(
                f"{NOWPAYMENTS_API_URL}/payment/{payment_id}",
                headers=headers,
                timeout=aiohttp.ClientTimeout(total=10)
            ) as response:
                if response.status == 200:
                    data = await response.json()
                    return data.get("payment_status", "waiting")
                return "error"
    except Exception:
        return "error"
