from __future__ import annotations

from typing import Any
from urllib.parse import quote

from flask import jsonify, request

from .. import settings


def register(app) -> None:
    """Expose the login URLs the frontend needs for auth state rendering."""

    @app.route("/api/auth/config", methods=["GET"])
    def auth_config() -> Any:
        """Render the auth configuration payload consumed by the SPA."""

        issuer = settings.KEYCLOAK_ISSUER
        public_origin = request.host_url.rstrip("/")
        redirect_uri = quote(f"{public_origin}/", safe="")
        login_url = (
            f"{issuer}/protocol/openid-connect/auth"
            f"?client_id={quote(settings.KEYCLOAK_CLIENT_ID, safe='')}"
            f"&redirect_uri={redirect_uri}"
            f"&response_type=code"
            f"&scope=openid"
        )
        reset_url = (
            f"{issuer}/login-actions/reset-credentials"
            f"?client_id={quote(settings.KEYCLOAK_CLIENT_ID, safe='')}"
            f"&redirect_uri={redirect_uri}"
        )
        account_url = f"{issuer}/account"
        account_password_url = f"{account_url}/#/security/signingin"

        if not settings.KEYCLOAK_ENABLED:
            return jsonify(
                {
                    "enabled": False,
                    "login_url": login_url,
                    "reset_url": reset_url,
                    "account_url": account_url,
                    "account_password_url": account_password_url,
                }
            )

        return jsonify(
            {
                "enabled": True,
                "url": settings.KEYCLOAK_URL,
                "realm": settings.KEYCLOAK_REALM,
                "client_id": settings.KEYCLOAK_CLIENT_ID,
                "login_url": login_url,
                "reset_url": reset_url,
                "account_url": account_url,
                "account_password_url": account_password_url,
            }
        )
