from __future__ import annotations

from sqlalchemy.ext.asyncio import AsyncSession

from shared.events import register_handler
from shared.models.domain_event import DomainEvent
from shared.services.registry import services


async def on_user_logged_in(event: DomainEvent, session: AsyncSession) -> None:
    payload = event.payload
    user_id = payload["user_id"]
    session_id = payload["session_id"]

    # Adopt cart items (if cart service is registered)
    if services.has("cart"):
        await services.cart.adopt_cart_for_user(session, user_id, session_id)

    # Adopt calendar entries and tickets (if calendar service is registered)
    if services.has("calendar"):
        await services.calendar.adopt_entries_for_user(session, user_id, session_id)
        await services.calendar.adopt_tickets_for_user(session, user_id, session_id)


register_handler("user.logged_in", on_user_logged_in)
