"""
Views for PatreonProvider
https://www.patreon.com/platform/documentation/oauth
"""

from __future__ import annotations

from django.http import HttpRequest

from allauth.socialaccount.adapter import get_adapter
from allauth.socialaccount.providers.oauth2.views import (
    OAuth2Adapter,
    OAuth2CallbackView,
    OAuth2LoginView,
)

from .constants import API_URL, PROVIDER_ID, USE_API_V2


class PatreonOAuth2Adapter(OAuth2Adapter):
    provider_id = PROVIDER_ID
    access_token_url = "https://www.patreon.com/api/oauth2/token"  # nosec
    authorize_url = "https://www.patreon.com/oauth2/authorize"
    profile_url = "{}/{}".format(
        API_URL,
        (
            "identity?include=memberships&fields%5Buser%5D=email,first_name,"
            "full_name,image_url,last_name,social_connections,"
            "thumb_url,url,vanity"
            if USE_API_V2
            else "current_user"
        ),
    )

    def complete_login(self, request: HttpRequest, app, token, **kwargs):
        headers = {"Authorization": f"Bearer {token.token}"}
        with get_adapter().get_requests_session() as sess:
            resp = sess.get(self.profile_url, headers=headers)
            extra_data = resp.json().get("data")

            if USE_API_V2:
                # Extract tier/pledge level for Patreon API v2:
                try:
                    memberships = extra_data["relationships"]["memberships"]
                    member_id = memberships["data"][0]["id"]
                    member_url = (
                        "{}/members/{}?include="
                        "currently_entitled_tiers&fields%5Btier%5D=title"
                    ).format(API_URL, member_id)
                    resp_member = sess.get(member_url, headers=headers)
                    resp_data = resp_member.json()
                    pledge_title = resp_data["included"][0]["attributes"]["title"]
                    extra_data["pledge_level"] = pledge_title
                except (KeyError, IndexError):
                    extra_data["pledge_level"] = None
                    pass

        return self.get_provider().sociallogin_from_response(request, extra_data)


oauth2_login = OAuth2LoginView.adapter_view(PatreonOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(PatreonOAuth2Adapter)
