"""
NEXIUM Blog API Example
A complete REST API with ORM, validation, and middleware
"""

from nexium import Nexium, Model, validate, Field
from typing import Optional

app = Nexium(
    title="Blog API",
    version="1.0.0",
    description="A simple blog API built with NEXIUM",
    debug=True,
    cors=True,
)


# Models
class Post(Model):
    """Blog post model."""
    __table__ = "posts"


class User(Model):
    """User model."""
    __table__ = "users"


# Middleware
@app.middleware()
async def logging_middleware(request, call_next):
    """Log all requests."""
    print(f"➡️  {request.method} {request.url.path}")
    response = await call_next(request)
    print(f"⬅️  Status: {response.status_code}")
    return response


# Routes
@app.get("/")
async def home():
    """API information."""
    return {
        "app": "Blog API",
        "version": "1.0.0",
        "endpoints": {
            "posts": "/posts",
            "users": "/users",
            "docs": "/docs (coming soon)"
        }
    }


# Posts endpoints
@app.get("/posts")
async def list_posts(limit: int = 10, offset: int = 0):
    """List all posts."""
    posts = await Post.all()
    total = len(posts)
    posts_paginated = posts[offset:offset+limit]
    
    return {
        "total": total,
        "limit": limit,
        "offset": offset,
        "posts": [p.dict() for p in posts_paginated]
    }


@app.get("/posts/{id}")
async def get_post(id: int):
    """Get post by ID."""
    post = await Post.get(id=id)
    if not post:
        return {"error": "Post not found"}, 404
    return post.dict()


@app.post("/posts")
@validate
async def create_post(
    title: str = Field(min_length=5, max_length=200),
    content: str = Field(min_length=10),
    author_id: int = Field(gt=0),
    published: bool = True
):
    """Create a new post."""
    post = Post(
        title=title,
        content=content,
        author_id=author_id,
        published=published
    )
    await post.save()
    return {"message": "Post created", "post": post.dict()}, 201


@app.put("/posts/{id}")
@validate
async def update_post(
    id: int,
    title: Optional[str] = Field(min_length=5, max_length=200),
    content: Optional[str] = Field(min_length=10),
    published: Optional[bool] = None
):
    """Update a post."""
    post = await Post.get(id=id)
    if not post:
        return {"error": "Post not found"}, 404
    
    if title:
        post.title = title
    if content:
        post.content = content
    if published is not None:
        post.published = published
    
    await post.save()
    return {"message": "Post updated", "post": post.dict()}


@app.delete("/posts/{id}")
async def delete_post(id: int):
    """Delete a post."""
    post = await Post.get(id=id)
    if not post:
        return {"error": "Post not found"}, 404
    
    await post.delete()
    return {"message": "Post deleted"}


# Users endpoints
@app.get("/users")
async def list_users():
    """List all users."""
    users = await User.all()
    return {"users": [u.dict() for u in users]}


@app.get("/users/{id}")
async def get_user(id: int):
    """Get user by ID."""
    user = await User.get(id=id)
    if not user:
        return {"error": "User not found"}, 404
    return user.dict()


@app.post("/users")
@validate
async def create_user(
    name: str = Field(min_length=3, max_length=100),
    email: str = Field(pattern=r"^[\w\.-]+@[\w\.-]+\.\w+$"),
    age: int = Field(ge=18, le=120)
):
    """Create a new user."""
    user = User(name=name, email=email, age=age)
    await user.save()
    return {"message": "User created", "user": user.dict()}, 201


# Stats endpoint
@app.get("/stats")
async def stats():
    """Get API statistics."""
    post_count = await Post.count()
    user_count = await User.count()
    
    return {
        "posts": post_count,
        "users": user_count,
        "framework": "NEXIUM",
        "status": "operational"
    }


if __name__ == "__main__":
    print("""
╔══════════════════════════════════════════════════════════╗
║                    NEXIUM BLOG API                       ║
╚══════════════════════════════════════════════════════════╝

📝 Example API showcasing NEXIUM features:
   ✅ ORM (DATAVOXEL)
   ✅ Validation (INTEGRIUM)
   ✅ Routing
   ✅ Middleware
   ✅ CORS

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