"""
Openshift OAuth2 backend
"""

from typing import Any, cast
from urllib.parse import urljoin

from social_core.utils import append_slash

from .oauth import BaseOAuth2


class OpenshiftOAuth2(BaseOAuth2):
    name = "openshift"

    def access_token_url(self):
        return urljoin(append_slash(cast("str", self.setting("URL"))), "oauth/token")

    def authorization_url(self):
        return urljoin(
            append_slash(cast("str", self.setting("URL"))), "oauth/authorize"
        )

    def get_user_id(self, details, response):
        return response["metadata"]["uid"]

    def get_user_details(self, response):
        """Return user details from openshift account"""
        username = response["metadata"]["name"]
        email = response["metadata"]["name"]
        return {"username": username, "email": email}

    def user_data(self, access_token: str, *args, **kwargs) -> dict[str, Any] | None:
        """Loads user data from service"""
        headers = {"Authorization": f"Bearer {access_token}"}

        return self.request(
            urljoin(append_slash(cast("str", self.setting("URL"))), "oapi/v1/users/~"),
            headers=headers,
        ).json()
