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

import logging


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

# Инициализация приложения
app = FastAPI()

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

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

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

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

# Обработка 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()