from .models import TenantConfig, OidcBffConfig, OidcSharedSettings


def resolve_oidc_config(
    tenant_cfg: TenantConfig,
    shared: OidcSharedSettings,
    public_base_url_override: str | None = None,
) -> OidcBffConfig:

    if not tenant_cfg.oidc:
        raise ValueError(
            f"bff_oidc mancante per tenant '{tenant_cfg.name or 'unknown'}'"
        )

    realm = tenant_cfg.oidc.realm
    issuer = f"{shared.base_url.rstrip('/')}/{realm}"

    client_id = tenant_cfg.oidc.client_id or shared.client_id
    scope = tenant_cfg.oidc.scope or shared.scope
    auth_method = tenant_cfg.oidc.auth_method or shared.auth_method
    redirect_path = tenant_cfg.oidc.redirect_path or shared.redirect_path

    tenant_public = tenant_cfg.oidc.public_base_url
    public = (
        public_base_url_override
        or tenant_public
        or shared.public_base_url
    ).rstrip("/")

    return OidcBffConfig(
        realm=realm,
        issuer=issuer,
        authorization_endpoint=f"{issuer}/protocol/openid-connect/auth",
        token_endpoint=f"{issuer}/protocol/openid-connect/token",
        revocation_endpoint=f"{issuer}/protocol/openid-connect/revoke",
        end_session_endpoint=f"{issuer}/protocol/openid-connect/logout",
        jwks_uri=f"{issuer}/protocol/openid-connect/certs",
        client_id=client_id,
        redirect_uri=f"{public}{redirect_path}",
        post_logout_redirect_uri=f"{public}{redirect_path}",
        scope=scope,
        token_endpoint_auth_method=auth_method,
    )