"""MyFatoorah payment integration for promotions.

Uses the shared MyFatoorahClient to create invoice links for promotion purchases.
"""

from __future__ import annotations

from apps.core.myfatoorah_client import get_client


def create_payment_link(
    *,
    customer_name: str,
    customer_email: str,
    customer_mobile: str,
    amount: float,
    description: str,
    reference: str,
    language: str = "en",
) -> dict:
    """
    Create an invoice link via MyFatoorah SendPayment API.

    Returns dict with keys: invoice_url, invoice_id.
    Raises MyFatoorahError / MyFatoorahValidationError on failure.
    """
    client = get_client()

    # Strip country code prefix for the mobile field
    mobile = customer_mobile.replace("+971", "").replace("+", "").lstrip("0")

    payload = {
        "CustomerName": customer_name or "Rofoof User",
        "NotificationOption": "LNK",
        "InvoiceValue": amount,
        "DisplayCurrencyIso": "AED",
        "MobileCountryCode": "+971",
        "CustomerMobile": mobile,
        "CustomerEmail": customer_email or "",
        "CustomerReference": reference,
        "Language": language.upper() if language in ("en", "ar") else "EN",
        "InvoiceItems": [
            {
                "ItemName": description,
                "Quantity": 1,
                "UnitPrice": amount,
            }
        ],
    }

    result = client.send_payment(payload)

    return {
        "invoice_url": result["InvoiceURL"],
        "invoice_id": result["InvoiceId"],
    }
