from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.database import Base, engine
from app.controllers import {{ default_resource }}_controller
{% if use_auth %}
from app.auth.routers import (
    auth_router,
    register_router,
    reset_password_router,
    users_router  # <-- NEW: Import the users_router
)
{% if use_oauth %}
from app.auth.routers import google_oauth_router
{% endif %}
{% endif %}
# V-- Auto-include new controllers here --V


# Lifespan manager to handle startup events
@asynccontextmanager
async def lifespan(app: FastAPI):
    # This creates all tables defined in your models on startup.
    # In a production app with Alembic, this would be removed.
    {% if is_async %}
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    {% endif %}
    yield
    # Code in this block would run on shutdown


app = FastAPI(
    title="{{ project_name }}",
    description="A project generated by fast-boiler.",
    version="1.0.0",
    lifespan=lifespan
)

# CORS Middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# Include the main resource router (e.g., for users)
# This now provides the admin-only, paginated GET /users endpoint
app.include_router({{ default_resource }}_controller.router)

{% if use_auth %}
# Include the authentication routers
app.include_router(auth_router, prefix="/auth/jwt", tags=["auth"])
app.include_router(register_router, prefix="/auth", tags=["auth"])
app.include_router(reset_password_router, prefix="/auth", tags=["auth"])

# 👇 NEW: Include the router for self-service and admin user management
app.include_router(users_router, prefix="/users", tags=["users"])

{% if use_oauth and google_oauth_router %}
app.include_router(google_oauth_router, prefix="/auth/google", tags=["auth"])
{% endif %}
{% endif %}

# V-- Auto-include new routers here --V


@app.get("/", tags=["Root"])
async def read_root():
    return {"message": "Welcome to the API!"}


{% if not is_async %}
# For sync projects, create tables here before the app starts
Base.metadata.create_all(bind=engine)
{% endif %}