from fastapi import Depends, Header
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.models.venue import Venue
from app.services.tenant_sync_service import resolve_current_venue


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

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


def get_portal_session_token(authorization: str | None = Header(default=None)) -> str | None:
    return normalize_portal_session_token(authorization)


def get_current_venue(
    db: Session = Depends(get_db),
    session_token: str | None = Depends(get_portal_session_token),
) -> Venue:
    return resolve_current_venue(session_token=session_token, db=db)


__all__ = ["Session", "get_db", "get_current_venue", "get_portal_session_token", "normalize_portal_session_token"]
