"""Establishing and tearing down the app's own session.

Scout keeps its own session cookie, entirely separate from any BW cookie: BW
proves who someone is once, at sign-in, and Scout tracks them from there. The
id_token is a one-shot bootstrap — verified, read, and discarded here. It is
never stored, never put in a cookie, and never treated as a bearer token.
"""

from sqlalchemy.orm import Session as DbSession
from starlette.requests import Request

from app.constants import DEFAULT_LEVEL
from app.models.account import Account
from app.services import accounts, levels
from app.services.authz import SESSION_USER_KEY


def establish(request: Request, db: DbSession, identity: dict) -> Account:
    """Turn a verified BW identity into a signed-in Scout session.

    The identity comes either from a verified id_token or from /app/userinfo —
    both are trusted, both carry the same fields.
    """
    account = accounts.upsert_from_bw_identity(db, identity, initial_level=DEFAULT_LEVEL)
    request.session[SESSION_USER_KEY] = account.username
    levels.report_access(account.username)
    return account


def clear(request: Request) -> None:
    request.session.clear()
