from __future__ import annotations

from quart import (
    make_response, Blueprint, g, request
)

from shared.infrastructure.actions import call_action
from shared.infrastructure.data_client import fetch_data
from shared.browser.app.authz import require_admin
from shared.sx.helpers import sx_response


def register():
    bp = Blueprint("page_admin", __name__)

    @bp.put("/payments/")
    @require_admin
    async def update_sumup(**kwargs):
        """Update SumUp credentials for this page (writes to blog's db_blog)."""
        page_post = getattr(g, "page_post", None)
        if not page_post:
            return await make_response("Page not found", 404)

        form = await request.form
        merchant_code = (form.get("merchant_code") or "").strip()
        api_key = (form.get("api_key") or "").strip()
        checkout_prefix = (form.get("checkout_prefix") or "").strip()

        payload = {
            "container_type": "page",
            "container_id": page_post.id,
            "sumup_merchant_code": merchant_code,
            "sumup_checkout_prefix": checkout_prefix,
        }
        if api_key:
            payload["sumup_api_key"] = api_key

        await call_action("blog", "update-page-config", payload=payload)

        # Re-fetch page config to get fresh data
        from types import SimpleNamespace
        raw_pc = await fetch_data(
            "blog", "page-config",
            params={"container_type": "page", "container_id": page_post.id},
            required=False,
        )
        g.page_config = SimpleNamespace(**raw_pc) if raw_pc else None

        from shared.sx.page import get_template_context
        from sxc.pages.renders import render_cart_payments_panel
        ctx = await get_template_context()
        html = render_cart_payments_panel(ctx)
        return sx_response(html)

    return bp
