from __future__ import annotations

from quart import Blueprint, g, make_response, url_for


from ..browse.routes import register as register_browse_bp

from .filters.qs import makeqs_factory
from ..browse.services.nav import get_nav
from ..api.routes import products_api
from .admin.routes import register as register_admin



def register(url_prefix, title):
  bp = Blueprint("market", __name__, url_prefix)

  @bp.before_request
  def route():
    g.makeqs_factory = makeqs_factory

  
  @bp.context_processor
  async def inject_root():
    market = getattr(g, "market", None)
    market_id = market.id if market else None
    post_data = getattr(g, "post_data", None) or {}
    return {
      **post_data,
      "market_title": market.name if market else title,
      "categories": (await get_nav(g.s, market_id=market_id))["cats"],
      "qs": makeqs_factory()(),
      "market": market,
    }

  bp.register_blueprint(
    register_browse_bp(),
  )
  bp.register_blueprint(
    products_api,
  )
  bp.register_blueprint(
    register_admin(),
  )

  
  
  return bp

