
import jwt
from django.conf import settings
import requests
from notifications.models import Notification
from utils.firebase import send_notification


def verify_token(request):
    authorization_header = request.headers.get('Authorization')
    if not authorization_header:
        return None
    try:
        access_token = authorization_header.split(' ')[1]
        payload = jwt.decode(access_token, settings.SECRET_KEY, algorithms='HS256')
        return (payload['user_id'])
    except jwt.ExpiredSignatureError:
        return None
    except jwt.exceptions.InvalidSignatureError:
        return None
    except IndexError:
        return None
    

def send_otp_to_phone(mobile, otp):
    try:
        url = settings.FAST2SMS_URL

        payload = {
            "mobile": str(mobile),
            "otp_id": settings.FAST2SMS_OTP_ID,
            "otp_expiry": 15,
            "otp_length": 6,
            "otp": str(otp),
            "variables_values": "value1|value2"
        }

        headers = {
            "authorization": settings.FAST2SMS_AUTH_KEY,
            "Content-Type": "application/json"
        }

        response = requests.post(
            url,
            json=payload,
            headers=headers,
            timeout=10
        )

        data = response.json()

        print(data)

        if(data.get("return") is True and data.get("status_code") == 200):
            return True

        return False

    except Exception as e:
        print(e)
        return False
    




def send_contract_notification(
    user,
    title,
    body,
    notification_type,
    reference_id=None,
    data=None
):
    """
    Save notification in DB + Send FCM
    """

    notification = Notification.objects.create(
        user=user,
        title=title,
        body=body,
        notification_type=notification_type,
        reference_id=reference_id,
        metadata=data
    )

    try:

        if user.fcm_token:

            payload = {
                "type": str(notification_type),
                "reference_id": str(reference_id or "")
            }

            if data:
                payload.update(
                    {
                        str(k): str(v)
                        for k, v in data.items()
                    }
                )

            send_notification(
                title=title,
                message=body,
                token=user.fcm_token,
                data=payload
            )

    except Exception as e:
        print("FCM Error:", str(e))

    return notification