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
from .clear_cart_for_order import clear_cart_for_order


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,
            })

            # Clear cart only after payment is confirmed
            page_post_id = page_config.container_id if page_config else None
            await clear_cart_for_order(session, order, page_post_id=page_post_id)

            await emit_activity(
                session,
                activity_type="rose:OrderPaid",
                actor_uri="internal:cart",
                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()
