from __future__ import annotations

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

from .services.markets import (
    create_market as svc_create_market,
    soft_delete as svc_soft_delete,
)

from shared.browser.app.redis_cacher import clear_cache
from shared.browser.app.authz import require_admin
from shared.sx.helpers import sx_response


def register():
    bp = Blueprint("markets", __name__, url_prefix='/markets')

    @bp.context_processor
    async def inject_root():
        return {}

    @bp.post("/new/")
    @require_admin
    async def create_market(**kwargs):
        form = await request.form
        name = (form.get("name") or "").strip()

        post_data = getattr(g, "post_data", None)
        post_id = (post_data.get("post") or {}).get("id") if post_data else None

        if not post_id:
            post_id = form.get("post_id")
            if post_id:
                post_id = int(post_id)

        try:
            await svc_create_market(g.s, post_id, name)
        except Exception as e:
            from shared.sx.jinja_bridge import render as render_comp
            return await make_response(render_comp("error-inline", message=str(e)), 422)

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

    @bp.delete("/<market_slug>/")
    @require_admin
    async def delete_market(market_slug: str, **kwargs):
        post_slug = getattr(g, "post_slug", None)
        deleted = await svc_soft_delete(g.s, post_slug, market_slug)
        if not deleted:
            return await make_response("Market not found", 404)

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

    return bp
