"""
Refund PayPal payment function - standalone.
"""

import asyncio
import httpx
from typing import Dict, Any, Optional

from apexsaas.infrastructure.paypal.client import PayPalClient
from apexsaas.exceptions import ApexValidationError, ApexPaymentError


async def refund_payment(
    capture_id: str,
    amount: Optional[str] = None,
    currency: str = "USD",
    client_id: str = None,
    client_secret: str = None,
    sandbox: bool = True
) -> Dict[str, Any]:
    """
    Refund a PayPal payment (async).
    
    Args:
        capture_id: PayPal capture ID
        amount: Refund amount (optional, full refund if not provided)
        currency: Currency code (default: "USD")
        client_id: PayPal client ID
        client_secret: PayPal client secret
        sandbox: Use sandbox mode (default: True)
    
    Returns:
        dict with refund data
    
    Raises:
        ApexValidationError: If input validation fails
        ApexPaymentError: If PayPal API call fails
    """
    if not capture_id:
        raise ApexValidationError("capture_id is required")
    
    # Get credentials from environment if not provided
    import os
    client_id = client_id or os.getenv("PAYPAL_CLIENT_ID")
    client_secret = client_secret or os.getenv("PAYPAL_CLIENT_SECRET")
    
    if not client_id or not client_secret:
        raise ApexValidationError("PayPal credentials required (client_id and client_secret)")
    
    client = PayPalClient(
        client_id=client_id,
        client_secret=client_secret,
        mode="sandbox" if sandbox else "live"
    )
    
    data = {}
    if amount:
        data["amount"] = {
            "value": str(amount),
            "currency_code": currency.upper()
        }
    
    async with httpx.AsyncClient() as http_client:
        token = await client._get_access_token()
        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json"
        }
        
        response = await http_client.post(
            f"{client.base_url}/v2/payments/captures/{capture_id}/refund",
            headers=headers,
            json=data
        )
        response.raise_for_status()
        return response.json()


def refund_payment_sync(
    capture_id: str,
    amount: Optional[str] = None,
    currency: str = "USD",
    client_id: str = None,
    client_secret: str = None,
    sandbox: bool = True
) -> Dict[str, Any]:
    """Sync wrapper for refund_payment."""
    from apexsaas.core.utils.async_runner import run_async
    try:
        return run_async(refund_payment(
            capture_id=capture_id,
            amount=amount,
            currency=currency,
            client_id=client_id,
            client_secret=client_secret,
            sandbox=sandbox
        ))
    except Exception as e:
        raise ApexPaymentError(f"Failed to refund payment: {str(e)}")
