from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from model.database import init_db
from routers import index, logins, users, product, profile, jobs, client, auth1
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware


import logging


# Создаём таблицы в БД
init_db()

# Инициализация приложения
app = FastAPI(title="API для turboapply",
              description="🚀 Это кастомное описание для Swagger UI",  # ✅ Описание
              version="1.0.3",                     # ✅ Версия API
            #   docs_url="/api/v1/documentation/",
              redoc_url=None,
            #   docs_url=None,  # Отключаем дефолтный Swagger
              openapi_url="/openapi.json", 
              swagger_ui_parameters={"filter": True},
            #   on_startup=[start_workers]
            )

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Разрешить запросы отовсюду (для тестов)
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Настройка шаблонов
templates = Jinja2Templates(directory="templates")

# Подключение статики (делаем это ОДИН раз)
app.mount("/static", StaticFiles(directory="static"), name="static")

# Подключение маршрутов
app.include_router(index.router, tags=["callback"], include_in_schema=False)
app.include_router(logins.router, tags=["login"], include_in_schema=False)
app.include_router(users.router, tags=["users"], include_in_schema=False)
app.include_router(product.router, tags=["product"], include_in_schema=False)
app.include_router(client.router, tags=["client"])
app.include_router(auth1.router, tags=["auth1"], include_in_schema=False)



# Подключение роутеров
app.include_router(profile.router, tags=["Profile"])
app.include_router(jobs.router, tags=["Jobs"], include_in_schema=False)

# Обработка 404
@app.exception_handler(404)
async def not_found(request: Request, exc: HTTPException):
    return templates.TemplateResponse("working.html", {"request": request}, status_code=404)

@app.exception_handler(HTTPException)
async def auth_exception_handler(request: Request, exc: HTTPException):
    if exc.status_code == 401:
        return RedirectResponse(url="/login")
    return RedirectResponse(url="/error")


@app.on_event("startup")
async def startup():
    await init_db()
    
    
class TokenRefreshMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        response = await call_next(request)
        
        # If new tokens were set during the request
        if hasattr(request.state, "new_tokens"):
            for cookie in request.state.new_tokens.cookies:
                response.set_cookie(
                    key=cookie.key,
                    value=cookie.value,
                    max_age=cookie.max_age,
                    expires=cookie.expires,
                    path=cookie.path,
                    domain=cookie.domain,
                    secure=cookie.secure,
                    httponly=cookie.http_only,
                    samesite=cookie.samesite
                )
        
        return response

app.add_middleware(TokenRefreshMiddleware)