# Generated by smithplates HTTP codegen. Do not edit.

from __future__ import annotations

from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from generated.widget_api.widget_api.api_exception_handler import FallbackApiExceptionHandler
from generated.widget_api.widget_api.api_exceptions import NotImplementedApiError
from generated.widget_api.widget_api.apis.v1_widgets_api import router as V1WidgetsApiRouter
from generated.widget_api.widget_api.app_services import ApiServices


def configure_fallback_exception_handlers(
    app: FastAPI,
    fallback_exception_handler: FallbackApiExceptionHandler,
) -> None:
    @app.exception_handler(NotImplementedApiError)
    async def on_not_implemented(
        request: Request,
        exc: NotImplementedApiError,
    ) -> JSONResponse:
        return await fallback_exception_handler.handle_not_implemented(request, exc)

    @app.exception_handler(RequestValidationError)
    async def on_validation_error(
        request: Request,
        exc: RequestValidationError,
    ) -> JSONResponse:
        return await fallback_exception_handler.handle_validation_error(request, exc)

    @app.exception_handler(Exception)
    async def on_unexpected_error(request: Request, exc: Exception) -> JSONResponse:
        return await fallback_exception_handler.handle_unexpected(request, exc)


def configure_services(app: FastAPI, services: ApiServices) -> None:
    app.state.api_services = services
    app.include_router(V1WidgetsApiRouter)


def create_app(
    services: ApiServices,
    fallback_exception_handler: FallbackApiExceptionHandler,
) -> FastAPI:
    app = FastAPI(
        title="WidgetApi",
        description=None,
        version="1",
    )
    configure_services(app, services)
    configure_fallback_exception_handlers(app, fallback_exception_handler)
    return app
