"""
Cart identity resolution — shared across all apps that need to know
who the current cart owner is (user_id or anonymous session_id).
"""
from __future__ import annotations

import secrets
from typing import TypedDict, Optional

from quart import g, session as qsession


class CartIdentity(TypedDict):
    user_id: Optional[int]
    session_id: Optional[str]


def current_cart_identity() -> CartIdentity:
    """
    Decide how to identify the cart:

    - If user is logged in -> use user_id (and ignore session_id)
    - Else -> generate / reuse an anonymous session_id stored in Quart's session
    """
    user = getattr(g, "user", None)
    if user is not None and getattr(user, "id", None) is not None:
        return {"user_id": user.id, "session_id": None}

    sid = qsession.get("cart_sid")
    if not sid:
        sid = secrets.token_hex(16)
        qsession["cart_sid"] = sid

    return {"user_id": None, "session_id": sid}
