# [DEF:backend.src.core.auth.oauth:Module]
#
# @SEMANTICS: auth, oauth, oidc, adfs
# @PURPOSE:   ADFS OIDC configuration and client using Authlib.
# @LAYER:     Core
# @RELATION:  DEPENDS_ON -> authlib
# @RELATION:  USES -> backend.src.core.auth.config.auth_config
#
# @INVARIANT: Must use secure OIDC flows.

# [SECTION: IMPORTS]
from authlib.integrations.starlette_client import OAuth
from .config import auth_config
# [/SECTION]

# [DEF:oauth:Variable]
# @PURPOSE: Global Authlib OAuth registry.
oauth = OAuth()
# [/DEF:oauth:Variable]

# [DEF:register_adfs:Function]
# @PURPOSE: Registers the ADFS OIDC client.
# @PRE:     ADFS configuration is provided in auth_config.
# @POST:    ADFS client is registered in oauth registry.
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'
            }
        )
# [/DEF:register_adfs:Function]

# [DEF:is_adfs_configured:Function]
# @PURPOSE: Checks if ADFS is properly configured.
# @PRE:     None.
# @POST:    Returns True if ADFS client is registered, False otherwise.
# @RETURN:  bool - Configuration status.
def is_adfs_configured() -> bool:
    """Check if ADFS OAuth client is registered."""
    return 'adfs' in oauth._registry
# [/DEF:is_adfs_configured:Function]

# Initial registration
register_adfs()

# [/DEF:backend.src.core.auth.oauth:Module]