import json
import logging
import uuid

import httpx
from google.auth.transport import requests as google_requests
from google.oauth2 import service_account
from sqlalchemy.orm import Session

from app.core.config import settings
from app.models.device_token import DeviceToken

logger = logging.getLogger("yeneb.push")

_SCOPES = ["https://www.googleapis.com/auth/firebase.messaging"]
_credentials: service_account.Credentials | None = None


def register_device_token(
    db: Session, user_id: uuid.UUID, token: str, platform: str | None
) -> DeviceToken:
    """token is globally unique (see app.models.device_token.DeviceToken)
    — a re-registration of the same physical install upserts owner/
    platform instead of creating a duplicate row, which also quietly
    handles a different account logging in on the same device."""
    device = db.query(DeviceToken).filter(DeviceToken.token == token).first()
    if device is None:
        device = DeviceToken(user_id=user_id, token=token, platform=platform)
        db.add(device)
    else:
        device.user_id = user_id
        device.platform = platform
    db.commit()
    db.refresh(device)
    return device


def unregister_device_token(db: Session, user_id: uuid.UUID, token: str) -> None:
    db.query(DeviceToken).filter(
        DeviceToken.token == token, DeviceToken.user_id == user_id
    ).delete()
    db.commit()


def _get_access_token() -> str:
    global _credentials
    if _credentials is None:
        info = json.loads(settings.fcm_service_account_json)
        _credentials = service_account.Credentials.from_service_account_info(
            info, scopes=_SCOPES
        )
    if not _credentials.valid:
        _credentials.refresh(google_requests.Request())
    return _credentials.token


def _send_to_token(
    db: Session, device: DeviceToken, title: str, body: str, data: dict | None
) -> None:
    """Best-effort by design: a push failure must never break the
    order/delivery action that triggered it (see call sites in
    app.services.order_notifications), so every failure is caught and
    logged here rather than raised. An UNREGISTERED token (FCM's way
    of saying the app was uninstalled or the token is stale) is
    deleted outright — see the DeviceToken docstring."""
    message: dict = {
        "message": {
            "token": device.token,
            "notification": {"title": title, "body": body},
        }
    }
    if data:
        message["message"]["data"] = {k: str(v) for k, v in data.items()}

    try:
        access_token = _get_access_token()
        response = httpx.post(
            f"https://fcm.googleapis.com/v1/projects/{settings.fcm_project_id}/messages:send",
            headers={"Authorization": f"Bearer {access_token}"},
            json=message,
            timeout=10.0,
        )
        if response.status_code == 404:
            db.query(DeviceToken).filter(DeviceToken.id == device.id).delete()
            db.commit()
            return
        response.raise_for_status()
    except Exception:
        logger.exception("Failed to send push notification to device %s", device.id)


def notify_user(
    db: Session,
    user_id: uuid.UUID,
    title: str,
    body: str,
    data: dict | None = None,
) -> None:
    """Every push notification in this codebase goes through this one
    function. Only makes real FCM calls when both fcm_project_id and
    fcm_service_account_json are configured — otherwise (local dev,
    tests) this just logs, same log-only-until-configured pattern as
    app.services.sms.send_sms."""
    logger.info("Push to %s: %s - %s", user_id, title, body)
    if not settings.fcm_project_id or not settings.fcm_service_account_json:
        return

    devices = db.query(DeviceToken).filter(DeviceToken.user_id == user_id).all()
    for device in devices:
        _send_to_token(db, device, title, body, data)
