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

from .config import settings
from .db import database, Base, engine
from .routes import shortener_router

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.get_allow_origins(),
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.on_event("startup")
async def startup():
    await database.connect()

    # create tables if they don't exist
    Base.metadata.create_all(bind=engine)

@app.on_event("shutdown")
async def shutdown():
    await database.disconnect()

app.include_router(shortener_router)
