from urllib.parse import urlparse
from quart import session

from shared.infrastructure.urls import federation_url


LOGIN_REDIRECT_SESSION_KEY = "login_redirect_to"


def store_login_redirect_target() -> None:
    from quart import request

    target = request.args.get("next")
    if not target:
        ref = request.referrer or ""
        try:
            parsed = urlparse(ref)
            target = parsed.path or ""
        except Exception:
            target = ""

    if not target:
        return

    # Accept both relative paths and absolute URLs (cross-app redirects)
    if target.startswith("http://") or target.startswith("https://"):
        session[LOGIN_REDIRECT_SESSION_KEY] = target
    elif target.startswith("/") and not target.startswith("//"):
        session[LOGIN_REDIRECT_SESSION_KEY] = target


def pop_login_redirect_target() -> str:
    path = session.pop(LOGIN_REDIRECT_SESSION_KEY, None)
    if not path or not isinstance(path, str):
        return federation_url("/")

    # Absolute URL: return as-is (cross-app redirect)
    if path.startswith("http://") or path.startswith("https://"):
        return path

    # Relative path: must start with / and not //
    if path.startswith("/") and not path.startswith("//"):
        return federation_url(path)

    return federation_url("/")
