"""caprail make middleware <Name>"""
from __future__ import annotations
from pathlib import Path
import typer
from rich.console import Console

console = Console()

TEMPLATE = '''"""
{name} middleware.
"""
from __future__ import annotations

from caprail.http.middleware import Middleware, NextCallable
from caprail.http.request import Request
from caprail.http.response import Response


class {name}(Middleware):

    async def handle(self, request: Request, next: NextCallable) -> Response:
        # Add your middleware logic here
        response = await next(request)
        return response
'''

def command(name: str = typer.Argument(..., help="Middleware class name")) -> None:
    """Generate a new middleware class."""
    if not name.endswith("Middleware"):
        name += "Middleware"
    dest = Path.cwd() / "app" / "Http" / "Middleware" / f"{name}.py"
    dest.parent.mkdir(parents=True, exist_ok=True)
    if dest.exists():
        console.print(f"[yellow]Middleware already exists:[/] {dest}")
        raise typer.Exit(1)
    dest.write_text(TEMPLATE.format(name=name))
    console.print(f"[green]Middleware created:[/] {dest}")
