from ariadne import graphql
from starlette.requests import Request
from starlette.responses import JSONResponse

from api.route import Route
from api_graphql.service.schema import schema
from core.logger import Logger

BasePath = f"/api/graphql"
logger = Logger(__name__)


@Route.post(f"{BasePath}")
async def graphql_endpoint(request: Request):
    data = await request.json()

    # Note: Passing the request to the context is optional.
    # In Starlette, the current request is accessible as request
    success, result = await graphql(schema, data, context_value=request)

    status_code = 200
    if "errors" in result:
        status_codes = [
            error.get("extensions", {}).get("code", 200) for error in result["errors"]
        ]
        status_code = max(status_codes, default=200)

    return JSONResponse(result, status_code=status_code)
