from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from contextlib import asynccontextmanager
import mongoengine

from app.config.settings import Config
from app.api.v1.auth import router as auth_router


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    config = Config()
    mongoengine.connect(host=config.MONGODB_URI)
    yield
    # Shutdown
    mongoengine.disconnect()


app = FastAPI(
    title="Authentication Service API",
    version="1.0",
    description="""
    <p>The Authentication Service API is dedicated to user authentication and access control.</p>
    <p>It provides secure and robust authentication mechanisms for user login, registration, and management.</p>
    <p>This service ensures the protection of user data and identity, making it an ideal solution for building a secure user authentication system for your applications.</p>
    """,
    lifespan=lifespan
)

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

# Include routers
app.include_router(auth_router, prefix="/api")


@app.get("/", response_class=HTMLResponse)
async def home():
    return "<h1>Welcome to the Authentication Service API</h1><p>Go to <a href='/docs'>Swagger UI</a></p>"


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


@app.exception_handler(400)
async def bad_request_error(request, exc):
    return {
        "error": "Bad Request",
        "msg": "The request you made was invalid. Please check your input data and try again."
    }


@app.exception_handler(401)
async def unauthorized_error(request, exc):
    return {
        "error": "Unauthorized",
        "msg": "You are not authorized to access this resource. Please log in and provide valid credentials."
    }


@app.exception_handler(403)
async def forbidden_error(request, exc):
    return {
        "error": "Forbidden",
        "msg": "You do not have permission to access this resource."
    }


@app.exception_handler(404)
async def page_not_found(request, exc):
    return {
        "error": "Not Found",
        "msg": "The requested URL was not found on the server."
    }