from dataclasses import dataclass

from google.auth.transport import requests as google_requests
from google.oauth2 import id_token as google_id_token

from app.core.config import settings


class GoogleTokenError(Exception):
    """A submitted Google ID token couldn't be verified as submitted."""


@dataclass
class GoogleAccount:
    sub: str
    email: str
    name: str


def verify_google_id_token(token: str) -> GoogleAccount:
    """Verifies a Google-issued ID token's signature, audience, and
    expiry using Google's own public keys (google-auth handles key
    rotation/caching internally) and returns the identity it vouches
    for. Raises GoogleTokenError on anything invalid — expired,
    wrong audience, bad signature, or an email Google itself hasn't
    verified (email_verified=False), which is not worth trusting for
    account creation/linking here.

    Requires google_oauth_client_id to be configured; without it we
    can't say what audience to check against, so this refuses to run
    at all rather than skipping verification — unlike the SMS/email/
    Chapa services, there's no safe log-only fallback for a signature
    check. Tests monkeypatch this function directly instead (see
    tests/test_google_auth.py), same as chapa_service.verify_payment
    is monkeypatched in tests/test_payments.py.
    """
    if not settings.google_oauth_client_id:
        raise GoogleTokenError("Google Sign-In isn't configured.")

    try:
        payload = google_id_token.verify_oauth2_token(
            token, google_requests.Request(), settings.google_oauth_client_id
        )
    except ValueError as exc:
        raise GoogleTokenError("Invalid Google sign-in token.") from exc

    if not payload.get("email_verified", False):
        raise GoogleTokenError("Google hasn't verified this account's email.")

    email = payload.get("email")
    sub = payload.get("sub")
    if not email or not sub:
        raise GoogleTokenError("Invalid Google sign-in token.")

    return GoogleAccount(
        sub=sub, email=email.strip().lower(), name=payload.get("name") or ""
    )
