import requests
from django.conf import settings
import base64

#======================================================================
#Paypal Helper functions:
#-------------------------------------------------------------------

def get_paypal_base_url():
    """
    Returns PayPal API base URL based on PAYPAL_MODE.
    PAYPAL_MODE should be 'sandbox' or 'live'.
    """
    if getattr(settings, 'PAYPAL_MODE', 'sandbox') == 'live':
        return 'https://api-m.paypal.com'

    return 'https://api-m.sandbox.paypal.com'


def get_paypal_access_token():
    """
    Gets PayPal OAuth2 access token using client id and secret.
    """
    client_id = getattr(settings, 'PAYPAL_CLIENT_ID', None)
    client_secret = getattr(settings, 'PAYPAL_CLIENT_SECRET', None)

    if not client_id or not client_secret:
        raise Exception("PayPal client ID or secret is not configured.")

    base_url = get_paypal_base_url()
    token_url = f'{base_url}/v1/oauth2/token'

    auth_string = f'{client_id}:{client_secret}'
    encoded_auth = base64.b64encode(auth_string.encode()).decode()

    headers = {
        'Authorization': f'Basic {encoded_auth}',
        'Content-Type': 'application/x-www-form-urlencoded',
    }

    data = {
        'grant_type': 'client_credentials',
    }

    response = requests.post(
        token_url,
        headers=headers,
        data=data,
        timeout=30,
    )

    if response.status_code not in [200, 201]:
        raise Exception(f"PayPal token request failed: {response.text}")

    return response.json()['access_token']





def capture_paypal_order(order_id):
    """
    Captures approved PayPal order and returns PayPal capture response JSON.
    """
    access_token = get_paypal_access_token()
    base_url = get_paypal_base_url()

    capture_url = f'{base_url}/v2/checkout/orders/{order_id}/capture'

    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {access_token}',
        'PayPal-Request-Id': f'capture-{order_id}',
    }

    response = requests.post(
        capture_url,
        headers=headers,
        timeout=30,
    )

    if response.status_code not in [200, 201]:
        raise Exception(f"PayPal order capture failed: {response.text}")

    return response.json()


def get_paypal_approval_url(order_data):
    """
    Extracts PayPal approval URL from order creation response.
    """
    for link in order_data.get('links', []):
        if link.get('rel') == 'approve':
            return link.get('href')

    return None