# #region AuthOauthModule [C:2] [TYPE Module] [SEMANTICS auth, oauth, oidc, adfs, authlib]
#
# @BRIEF ADFS OIDC configuration and client using Authlib.
# @LAYER     Core
# @RELATION DEPENDS_ON -> [EXT:Library:authlib]
# @RELATION DEPENDS_ON -> [auth_config]
#
# @INVARIANT  Must use secure OIDC flows.

from authlib.integrations.starlette_client import OAuth

from .config import auth_config

# #region oauth [TYPE Variable]
# @BRIEF Global Authlib OAuth registry.
# @RELATION DEPENDS_ON -> [EXT:Library:OAuth]
oauth = OAuth()
# #endregion oauth

# #region register_adfs [TYPE Function]
# @BRIEF Registers the ADFS OIDC client.
# @PRE      ADFS configuration is provided in auth_config.
# @POST     ADFS client is registered in oauth registry.
# @RELATION DEPENDS_ON -> [oauth]
# @RELATION DEPENDS_ON -> [auth_config]
def register_adfs():
    if auth_config.ADFS_CLIENT_ID:
        oauth.register(
            name='adfs',
            client_id=auth_config.ADFS_CLIENT_ID,
            client_secret=auth_config.ADFS_CLIENT_SECRET,
            server_metadata_url=auth_config.ADFS_METADATA_URL,
            client_kwargs={
                'scope': 'openid email profile groups'
            }
        )
# #endregion register_adfs

# #region is_adfs_configured [TYPE Function]
# @BRIEF Checks if ADFS is properly configured.
# @PRE      None.
# @POST     Returns True if ADFS client is registered, False otherwise.
# @RELATION DEPENDS_ON -> [oauth]
def is_adfs_configured() -> bool:
    """Check if ADFS OAuth client is registered."""
    return 'adfs' in oauth._registry
# #endregion is_adfs_configured

# Initial registration
register_adfs()

# #endregion AuthOauthModule
