from __future__ import annotations

import logging

from sqlalchemy.ext.asyncio import AsyncSession

from shared.events import register_activity_handler
from shared.infrastructure.actions import call_action, ActionError
from shared.models.federation import APActivity

log = logging.getLogger(__name__)


async def on_user_logged_in(activity: APActivity, session: AsyncSession) -> None:
    data = activity.object_data
    user_id = data["user_id"]
    session_id = data["session_id"]
    payload = {"user_id": user_id, "session_id": session_id}

    for app, action in [
        ("cart", "adopt-cart-for-user"),
        ("events", "adopt-entries-for-user"),
        ("events", "adopt-tickets-for-user"),
    ]:
        try:
            await call_action(app, action, payload=payload)
        except ActionError:
            log.warning("Failed: %s/%s for user %s", app, action, user_id)


register_activity_handler("rose:Login", on_user_logged_in)
