"""
Thin client for Flutterwave's v3 Standard (hosted) checkout — the payer is
redirected to a Flutterwave-hosted page rather than embedding card fields
in-app, so only the secret key is ever used, only server-side.

Docs: https://developer.flutterwave.com/docs/collecting-payments/standard
"""
import requests
from django.conf import settings

FLW_BASE_URL = "https://api.flutterwave.com/v3"
TIMEOUT = 15


def _headers():
    return {
        "Authorization": f"Bearer {settings.FLUTTERWAVE_SECRET_KEY}",
        "Content-Type": "application/json",
    }


def initiate_payment(tx_ref, amount, currency, email, name, redirect_url, title, description, phone=""):
    """
    Creates a hosted checkout session. Returns the parsed JSON response;
    on success, response['data']['link'] is the URL to redirect the payer to.
    Raises requests.HTTPError on a non-2xx response.
    """
    payload = {
        "tx_ref": tx_ref,
        "amount": str(amount),
        "currency": currency,
        "redirect_url": redirect_url,
        # Card only would leave out how most people actually pay in Nigeria —
        # bank transfer and USSD are common enough to offer by default.
        "payment_options": "card,banktransfer,ussd",
        "customer": {"email": email, "name": name, "phonenumber": phone},
        "customizations": {"title": title, "description": description},
    }
    resp = requests.post(f"{FLW_BASE_URL}/payments", json=payload, headers=_headers(), timeout=TIMEOUT)
    resp.raise_for_status()
    return resp.json()


def verify_transaction(transaction_id):
    """
    Server-side verification of a completed transaction — never trust the
    status/amount in the browser redirect alone, always re-check with
    Flutterwave directly using the transaction id it gave us.
    """
    resp = requests.get(f"{FLW_BASE_URL}/transactions/{transaction_id}/verify", headers=_headers(), timeout=TIMEOUT)
    resp.raise_for_status()
    return resp.json()


def refund_transaction(transaction_id, amount=None):
    """
    Refunds a completed transaction. Omitting `amount` refunds the full
    original amount; Flutterwave supports partial refunds by passing a
    smaller one.

    Docs: https://developer.flutterwave.com/docs/refunds
    """
    payload = {}
    if amount is not None:
        payload["amount"] = str(amount)
    resp = requests.post(f"{FLW_BASE_URL}/transactions/{transaction_id}/refund", json=payload, headers=_headers(), timeout=TIMEOUT)
    resp.raise_for_status()
    return resp.json()
