"""Check SumUp checkout status and update order accordingly.

Moved from cart/bp/cart/services/check_sumup_status.py.
"""
from types import SimpleNamespace

from shared.browser.app.payments.sumup import get_checkout as sumup_get_checkout
from shared.events import emit_activity
from shared.infrastructure.actions import call_action
from shared.infrastructure.data_client import fetch_data


async def check_sumup_status(session, order, *, page_config=None):
    # Auto-fetch page_config from blog if order has one and caller didn't provide it
    if page_config is None and order.page_config_id:
        raw_pc = await fetch_data(
            "blog", "page-config-by-id",
            params={"id": order.page_config_id},
            required=False,
        )
        if raw_pc:
            page_config = SimpleNamespace(**raw_pc)

    checkout_data = await sumup_get_checkout(order.sumup_checkout_id, page_config=page_config)
    order.sumup_status = checkout_data.get("status") or order.sumup_status
    sumup_status = (order.sumup_status or "").upper()

    if sumup_status == "PAID":
        if order.status != "paid":
            order.status = "paid"
            await call_action("events", "confirm-entries-for-order", payload={
                "order_id": order.id, "user_id": order.user_id,
                "session_id": order.session_id,
            })
            await call_action("events", "confirm-tickets-for-order", payload={
                "order_id": order.id,
            })

            page_post_id = page_config.container_id if page_config else None
            await call_action("cart", "clear-cart-for-order", payload={
                "user_id": order.user_id,
                "session_id": order.session_id,
                "page_post_id": page_post_id,
            })

            await emit_activity(
                session,
                activity_type="rose:OrderPaid",
                actor_uri="internal:orders",
                object_type="rose:Order",
                object_data={
                    "order_id": order.id,
                    "user_id": order.user_id,
                },
                source_type="order",
                source_id=order.id,
            )
    elif sumup_status == "FAILED":
        order.status = "failed"
    else:
        order.status = sumup_status.lower() or order.status

    await session.flush()
