"""
OMNIWEB Auth Example - Zero-config authentication
"""

from omniweb import OmniWeb
from omniweb.auth import enable_auth, requires_auth

app = OmniWeb(title="Auth Example", debug=True)

# Enable authentication with all features
auth = enable_auth(
    app,
    providers=["google", "github"],
    enable_magic_links=True,
    enable_2fa=True,
    secret_key="your-secret-key-here"  # Use env var in production
)

# Public route
@app.get("/")
async def home():
    """Public homepage."""
    return {
        "message": "Welcome to OMNIWEB Auth Example!",
        "endpoints": {
            "register": "POST /auth/register",
            "login": "POST /auth/login",
            "me": "GET /auth/me (requires auth)",
            "protected": "GET /protected (requires auth)"
        }
    }

# Protected route using decorator
@app.get("/protected")
@requires_auth
async def protected_route(request):
    """Protected route - requires authentication."""
    return {
        "message": "This is a protected route!",
        "user": {
            "id": request.user.id,
            "email": request.user.email,
            "username": request.user.username
        }
    }

# Admin-only route
@app.get("/admin")
@requires_auth
async def admin_route(request):
    """Admin-only route."""
    # Check if user is admin (you can add role to User model)
    if not getattr(request.user, 'is_admin', False):
        return {"error": "Admin access required"}, 403
    
    return {
        "message": "Welcome admin!",
        "stats": await auth.get_stats()  # Custom method
    }


if __name__ == "__main__":
    print("""
╔════════════════════════════════════════╗
║  🔐 OMNIWEB Auth Example              ║
╚════════════════════════════════════════╝

Endpoints available:
  POST /auth/register      - Register new user
  POST /auth/login         - Login
  GET  /auth/me            - Get current user
  POST /auth/logout        - Logout
  POST /auth/magic-link    - Request magic link
  GET  /protected          - Protected route

Try it:
  1. Register: curl -X POST http://localhost:8000/auth/register \\
       -H "Content-Type: application/json" \\
       -d '{"email": "test@example.com", "password": "password123"}'
  
  2. Login: curl -X POST http://localhost:8000/auth/login \\
       -H "Content-Type: application/json" \\
       -d '{"email": "test@example.com", "password": "password123"}'
  
  3. Access protected: curl http://localhost:8000/protected \\
       -H "Authorization: Bearer YOUR_TOKEN_HERE"

Starting server...
    """)
    
    app.run(host="127.0.0.1", port=8000, reload=True)
