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


class GoogleAuthenticationError(ValueError):
    """Raised when a Google credential cannot be trusted for authentication."""


def verify_google_credential(credential):
    """Verify a Google ID token and return its trusted identity claims."""
    if not settings.GOOGLE_OAUTH_CLIENT_ID:
        raise GoogleAuthenticationError('Google sign-in is not configured.')

    try:
        claims = id_token.verify_oauth2_token(
            credential,
            google_requests.Request(),
            settings.GOOGLE_OAUTH_CLIENT_ID,
        )
    except (ValueError, TypeError) as exc:
        raise GoogleAuthenticationError('The Google credential is invalid or expired.') from exc

    if claims.get('iss') not in {'accounts.google.com', 'https://accounts.google.com'}:
        raise GoogleAuthenticationError('The Google credential has an invalid issuer.')

    email = str(claims.get('email') or '').strip().lower()
    if not email or claims.get('email_verified') is not True:
        raise GoogleAuthenticationError('Google must provide a verified email address.')

    subject = str(claims.get('sub') or '').strip()
    if not subject:
        raise GoogleAuthenticationError('The Google credential has no account identifier.')

    return {
        'subject': subject,
        'email': email,
        'first_name': str(claims.get('given_name') or '').strip(),
        'last_name': str(claims.get('family_name') or '').strip(),
    }
