from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from mongoengine import connect, disconnect
from app.config.settings import Config
from app.api.v1.account import router as account_router


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    config = Config()
    connect(
        db=config.MONGODB_DB,
        host=config.MONGODB_HOST,
        port=config.MONGODB_PORT,
        username=config.MONGODB_USERNAME,
        password=config.MONGODB_PASSWORD,
        authentication_source='admin'
    )
    yield
    # Shutdown
    disconnect()


app = FastAPI(
    title="Account Management Service API",
    description="API for managing user accounts and profiles",
    version="1.0.0",
    lifespan=lifespan
)

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

# Include routers
app.include_router(account_router, prefix="/api/account", tags=["account"])


@app.get("/")
async def home():
    return {"message": "Welcome to the Account Management Service API", "docs": "/docs"}


# Global exception handlers
@app.exception_handler(500)
async def internal_server_error_handler(request: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content={
            "error": "Internal Server Error",
            "msg": "An internal server error occurred while processing your request."
        }
    )


@app.exception_handler(400)
async def bad_request_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=400,
        content={
            "error": "Bad Request",
            "msg": "The request could not be understood or was missing required parameters."
        }
    )


@app.exception_handler(401)
async def unauthorized_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=401,
        content={
            "error": "Unauthorized",
            "msg": "Authentication is required to access this resource."
        }
    )


@app.exception_handler(403)
async def forbidden_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=403,
        content={
            "error": "Forbidden",
            "msg": "You do not have permission to access this resource."
        }
    )


@app.exception_handler(404)
async def not_found_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=404,
        content={
            "error": "Not Found",
            "msg": "The requested resource could not be found."
        }
    )