"""Google-specific HTTP adapter. Never log responses or OAuth credentials."""

import httpx


class GoogleOAuthError(Exception):
    def __init__(self, code="provider_unavailable"):
        self.code = code
        super().__init__(code)


class GoogleOAuthClient:
    async def token(self, **data):
        async with httpx.AsyncClient(timeout=20) as client:
            try:
                response = await client.post("https://oauth2.googleapis.com/token", data=data)
                payload = response.json()
            except (httpx.HTTPError, ValueError):
                raise GoogleOAuthError() from None
        if response.is_error:
            code = payload.get("error")
            raise GoogleOAuthError(
                code
                if code in {"invalid_grant", "interaction_required", "login_required"}
                else "provider_unavailable"
            )
        if not payload.get("access_token"):
            raise GoogleOAuthError()
        return payload

    async def userinfo(self, token):
        async with httpx.AsyncClient(timeout=20) as client:
            try:
                response = await client.get(
                    "https://openidconnect.googleapis.com/v1/userinfo",
                    headers={"Authorization": f"Bearer {token}"},
                )
                response.raise_for_status()
                payload = response.json()
            except (httpx.HTTPError, ValueError):
                raise GoogleOAuthError() from None
        if not payload.get("sub") or payload.get("email_verified") is not True:
            raise GoogleOAuthError("identity_not_verified")
        return payload
