"""
Copyright (c) 2018 Noderabbit Inc., d.b.a. Appsembler

All rights reserved.

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

See https://nicksnettravels.builttoroam.com/post/2017/01/24/Verifying-Azure-Active-Directory-JWT-Tokens.aspx
    for verifying JWT tokens.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Literal

from social_core.exceptions import AuthException, AuthMissingParameter, AuthTokenError

from .azuread import AzureADOAuth2

if TYPE_CHECKING:
    from collections.abc import Mapping

    from requests.auth import AuthBase


class AzureADB2COAuth2(AzureADOAuth2):
    name = "azuread-b2c-oauth2"

    BASE_URL = "https://{authority_host}/{tenant_name}.onmicrosoft.com"
    AUTHORIZATION_URL = "{base_url}/oauth2/v2.0/authorize"
    OPENID_CONFIGURATION_URL = (
        "{base_url}/v2.0/.well-known/openid-configuration?p={policy}"
    )
    ACCESS_TOKEN_URL = "{base_url}/oauth2/v2.0/token?p={policy}"
    JWKS_URL = "{base_url}/discovery/v2.0/keys?p={policy}"
    DEFAULT_SCOPE = ["openid", "email"]
    EXTRA_DATA = [
        ("access_token", "access_token"),
        ("id_token", "id_token"),
        ("refresh_token", "refresh_token"),
        ("id_token_expires_in", "expires"),
        ("exp", "expires_on"),
        ("not_before", "not_before"),
        ("given_name", "first_name"),
        ("family_name", "last_name"),
        ("tfp", "policy"),
        ("token_type", "token_type"),
    ]

    @property
    def authority_host(self):
        return self.setting("AUTHORITY_HOST", f"{self.tenant_name}.b2clogin.com")

    @property
    def tenant_name(self):
        return self.setting("TENANT_NAME")

    @property
    def policy(self):
        policy = self.setting("POLICY")
        if not policy or not policy.lower().startswith("b2c_"):
            raise AuthException(
                self,
                "SOCIAL_AUTH_AZUREAD_B2C_OAUTH2_POLICY is "
                "required and should start with `b2c_`",
            )
        return policy

    @property
    def base_url(self):
        return self.BASE_URL.format(
            tenant_name=self.tenant_name, authority_host=self.authority_host
        )

    def openid_configuration_url(self):
        return self.OPENID_CONFIGURATION_URL.format(
            base_url=self.base_url, policy=self.policy
        )

    def get_access_token_url_format(self) -> dict[str, str]:
        params = super().get_access_token_url_format()
        params["policy"] = self.policy
        return params

    def jwks_url(self):
        return self.JWKS_URL.format(base_url=self.base_url, policy=self.policy)

    def request_access_token(
        self,
        url: str,
        method: Literal["GET", "POST", "DELETE"] = "GET",
        headers: Mapping[str, str | bytes] | None = None,
        data: dict | None = None,
        json: dict | None = None,
        auth: tuple[str, str] | AuthBase | None = None,
        params: dict | None = None,
    ) -> dict[Any, Any]:
        """
        This is probably a hack, but otherwise AzureADOAuth2 expects
        `access_token`.

        However, B2C backends provides `id_token`.
        """
        response = super().request_access_token(
            url,
            method=method,
            headers=headers,
            data=data,
            json=json,
            auth=auth,
            params=params,
        )
        if "access_token" not in response:
            response["access_token"] = response["id_token"]
        return response

    def auth_extra_arguments(self):
        """Return extra arguments needed on auth process."""
        extra_arguments = super().auth_extra_arguments()
        extra_arguments["p"] = self.policy
        return extra_arguments

    def get_user_id(self, details, response):
        """Use subject (sub) claim as unique id."""
        return response.get("sub")

    def get_user_details(self, response):
        """
        Email address is returned on a different attribute for AzureAD
        B2C backends.
        """
        details = super().get_user_details(response)
        if not details["email"] and response.get("emails"):
            details["email"] = response["emails"]
        if isinstance(details.get("email"), (list, tuple)):
            details["email"] = details["email"][0]
        return details

    def get_id_token_policy(self, claims: dict[str, Any]) -> str:
        policy = claims.get("tfp")
        if policy is None:
            policy = claims.get("acr")
        if not isinstance(policy, str) or not policy:
            raise AuthMissingParameter(self, "tfp")
        return policy

    def validate_id_token_policy(self, claims: dict[str, Any]) -> None:
        if self.get_id_token_policy(claims).lower() != self.policy.lower():
            raise AuthTokenError(self, "Token policy does not match configured policy")

    def validate_and_return_id_token(self, id_token: str) -> dict[str, Any]:
        claims = super().validate_and_return_id_token(id_token)
        self.validate_id_token_policy(claims)
        return claims

    def extra_data(
        self,
        user,
        uid: str,
        response: dict[str, Any],
        details: dict[str, Any],
        pipeline_kwargs: dict[str, Any],
    ) -> dict[str, Any]:
        data = super().extra_data(user, uid, response, details, pipeline_kwargs)
        if not data.get("policy") and response.get("acr"):
            data["policy"] = response["acr"]
        return data
