from fastapi import Depends, Header, HTTPException, status

from app.services.tenant_store import SessionIdentity, get_tenant_store


def _normalize_token(raw_value: str | None) -> str:
    if raw_value is None:
        return ""

    value = raw_value.strip()
    if value.lower().startswith("bearer "):
        return value.split(" ", 1)[1].strip()

    return value


def get_optional_session(authorization: str | None = Header(default=None)) -> SessionIdentity | None:
    token = _normalize_token(authorization)
    if not token:
        return None

    return get_tenant_store().get_session(token)


def require_session(session: SessionIdentity | None = Depends(get_optional_session)) -> SessionIdentity:
    if session is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Sessione non valida o assente")

    return session


def require_super_admin(session: SessionIdentity = Depends(require_session)) -> SessionIdentity:
    if session.role != "super_admin":
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Operazione riservata al super admin")

    return session


__all__ = ["get_optional_session", "require_session", "require_super_admin"]
