# 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 (
    InternalWidgetErrorApiError,
    NotImplementedApiError,
    WidgetNotFoundApiError,
)
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(WidgetNotFoundApiError)
    async def on_widget_not_found_api_error(
        request: Request,
        exc: WidgetNotFoundApiError,
    ) -> JSONResponse:
        return await fallback_exception_handler.handle_widget_not_found_api_error(request, exc)

    @app.exception_handler(InternalWidgetErrorApiError)
    async def on_internal_widget_error_api_error(
        request: Request,
        exc: InternalWidgetErrorApiError,
    ) -> JSONResponse:
        return await fallback_exception_handler.handle_internal_widget_error_api_error(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="""Golden case: service-level @httpError codegen (error models, api_exceptions,
api_exception_handler, app_factory exception registration) and Unit operation input.""",
        version="1",
    )
    configure_services(app, services)
    configure_fallback_exception_handlers(app, fallback_exception_handler)
    return app
