"""Sign in with Google — an additional signup/login option alongside the
existing email/password flow (never a replacement for it). The frontend
(Google Identity Services JS) hands us a signed ID token; we cryptographically
verify its signature against Google's public certs and check the audience
claim matches our own OAuth client ID before trusting anything inside it —
never just base64-decode and read the payload."""

from django.conf import settings
from google.auth.transport import requests as google_requests
from google.oauth2 import id_token


def verify_google_id_token(token):
    """Returns the verified claims dict (email, given_name, family_name,
    email_verified, ...), or None if the token is missing/invalid/expired,
    meant for a different app, or its email isn't itself Google-verified."""
    if not settings.GOOGLE_OAUTH_CLIENT_ID or not token:
        return None
    try:
        idinfo = id_token.verify_oauth2_token(token, google_requests.Request(), settings.GOOGLE_OAUTH_CLIENT_ID)
    except Exception:
        return None
    if not idinfo.get('email_verified') or not idinfo.get('email'):
        return None
    return idinfo
