from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.config import settings
from app.database import engine
from app.models.base import Base
from app.routers import auth, tickets, search, api_v1
from app.middleware import RateLimitMiddleware
from app.metrics import MetricsMiddleware, metrics_endpoint


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield


app = FastAPI(title=settings.app_name, version="0.1.0", lifespan=lifespan)

app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "https://sovet.itoservice.ru",
        "https://api.sovet.itoservice.ru",
        "http://sovet.itoservice.ru",
        "http://api.sovet.itoservice.ru",
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.add_middleware(MetricsMiddleware)
app.add_middleware(RateLimitMiddleware, requests_per_minute=30)

app.include_router(auth.router)
app.include_router(tickets.router)
app.include_router(search.router)
app.include_router(api_v1.router)

app.add_route("/api/metrics", metrics_endpoint, methods=["GET"])


@app.get("/api/health")
async def health():
    return {"status": "ok"}
