import base64
import requests
from datetime import datetime
from django.conf import settings


# ================= ACCESS TOKEN =================
def get_access_token():
    url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"

    try:
        response = requests.get(
            url,
            auth=(settings.MPESA_CONSUMER_KEY, settings.MPESA_CONSUMER_SECRET),
            timeout=10
        )
        response.raise_for_status()
        return response.json().get("access_token")
    except Exception:
        return None


# ================= STK PUSH =================
def stk_push(phone, amount, account_reference, transaction_desc):
    access_token = get_access_token()

    if not access_token:
        return {"ResponseCode": "1", "error": "Access token failed"}

    url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"

    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")

    password = base64.b64encode(
        (settings.MPESA_SHORTCODE + settings.MPESA_PASSKEY + timestamp).encode()
    ).decode("utf-8")

    payload = {
        "BusinessShortCode": settings.MPESA_SHORTCODE,
        "Password": password,
        "Timestamp": timestamp,
        "TransactionType": "CustomerPayBillOnline",
        "Amount": int(amount),
        "PartyA": phone,
        "PartyB": settings.MPESA_SHORTCODE,
        "PhoneNumber": phone,
        "CallBackURL": settings.MPESA_CALLBACK_URL,
        "AccountReference": account_reference,
        "TransactionDesc": transaction_desc,
    }

    headers = {
        "Authorization": f"Bearer {access_token}"
    }

    try:
        response = requests.post(url, json=payload, headers=headers, timeout=15)
        return response.json()
    except Exception:
        return {"ResponseCode": "1", "error": "Request failed"}