import json
import requests

from django.conf import settings

from google.oauth2 import service_account
from google.auth.transport.requests import Request


SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']


def get_access_token():

    credentials = service_account.Credentials.from_service_account_file(
        settings.FIREBASE_CREDENTIALS_PATH,
        scopes=SCOPES
    )

    request = Request()

    credentials.refresh(request)

    return credentials.token


def send_notification(
    title,
    message,
    topic=None,
    token=None,
    section=None,
    reference_id=None,
    image=None,
    data=None,
    sound=True
):

    try:

        access_token = get_access_token()

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

        notification_data = {}

        if section and reference_id:
            notification_data["link"] = (
                f"{settings.SERVER_URL}{section}/{reference_id}"
            )

        if data:
            notification_data.update(data)

        message_payload = {
            "notification": {
                "title": str(title),
                "body": str(message),
            },

            "data": {
                key: str(value)
                for key, value in notification_data.items()
            },

            "android": {
                "priority": "high",
                "notification": {
                    "sound": "default" if sound else None,
                }
            },

            "apns": {
                "payload": {
                    "aps": {
                        "sound": "default" if sound else "",
                        "content-available": 1,
                    }
                },
                "headers": {
                    "apns-priority": "10"
                }
            }
        }

        # add image
        if image:
            image_url = (
                image if image.startswith("http")
                else settings.SERVER_URL + image
            )

            message_payload["notification"]["image"] = image_url

        # topic notification
        if topic:
            message_payload["topic"] = topic

        # single device notification
        elif token:
            message_payload["token"] = token

        else:
            return {
                "success": False,
                "message": "Either topic or token is required"
            }

        payload = {
            "message": message_payload
        }

        response = requests.post(
            settings.FCM_URL,
            headers=headers,
            data=json.dumps(payload)
        )

        return {
            "success": response.status_code == 200,
            "status_code": response.status_code,
            "response": response.json()
        }

    except Exception as e:

        return {
            "success": False,
            "error": str(e)
        }