from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse

from ApiServices.AuthService.create_route import RouteRegisterController
from ApiServices.AuthService.endpoints.routes import get_routes
from ApiServices.AuthService.open_api_creator import create_openapi_schema
from ApiServices.AuthService.middlewares.token_middleware import token_middleware
from ApiServices.AuthService.config import api_config


def create_app():

    application = FastAPI(**api_config.api_info)
    application.add_middleware(
        CORSMiddleware,
        allow_origins=api_config.ALLOW_ORIGINS,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    @application.middleware("http")
    async def add_token_middleware(request: Request, call_next):
        return await token_middleware(request, call_next)

    @application.get("/", description="Redirect Route", include_in_schema=False)
    async def redirect_to_docs():
        return RedirectResponse(url="/docs")

    route_register = RouteRegisterController(app=application, router_list=get_routes())
    application = route_register.register_routes()

    application.openapi = lambda _=application: create_openapi_schema(_)
    return application
