import requests
from django.conf import settings


# ================= SMS =================
def send_sms(phone, message):
    if not phone:
        return False

    url = getattr(settings, "HOSTINGER_SMS_URL", "https://api.hostinger.com/sms/send")

    headers = {
        "Authorization": f"Bearer {settings.HOSTINGER_SMS_API_KEY}",
        "Content-Type": "application/json",
    }

    payload = {
        "to": phone,
        "message": message,
    }

    try:
        response = requests.post(url, json=payload, headers=headers, timeout=10)
        return response.status_code in [200, 201]
    except Exception:
        return False


# ================= IN-APP =================
def create_notification(user, title, message, n_type="system", unit=None):
    from payments.models import Notification  # lazy import

    return Notification.objects.create(
        user=user,
        title=title,
        message=message,
        notification_type=n_type,
        unit=unit
    )


# ================= MAIN NOTIFY =================
def notify_user(user, title, message, n_type="system", unit=None, send_sms_flag=True):
    # Always create in-app notification
    create_notification(user, title, message, n_type, unit)

    # Optional SMS
    if send_sms_flag:
        phone = getattr(user, "phone_number", None)
        if phone:
            send_sms(phone, message)


# ================= BROADCAST =================
def broadcast_to_tenants(tenants, title, message):
    for tenant in tenants:
        notify_user(
            tenant,
            title,
            message,
            n_type="announcement"
        )