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

console = Console()

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

from caprail.http.request import Request
from caprail.http.response import Response


class {name}:

    async def index(self, request: Request) -> Response:
        return Response.json({{"message": "Hello from {name}.index"}})

    async def create(self, request: Request) -> Response:
        return Response("Create form")

    async def store(self, request: Request) -> Response:
        data = await request.all()
        return Response.json(data, status=201)

    async def show(self, request: Request) -> Response:
        return Response.json({{"id": request.route("id")}})

    async def edit(self, request: Request) -> Response:
        return Response("Edit form")

    async def update(self, request: Request) -> Response:
        data = await request.all()
        return Response.json(data)

    async def destroy(self, request: Request) -> Response:
        return Response.no_content()
'''

RESOURCE_TEMPLATE = TEMPLATE  # same for now

def command(
    name: str = typer.Argument(..., help="Controller class name"),
    resource: bool = typer.Option(False, "--resource", "-r", help="Generate a resource controller"),
) -> None:
    """Generate a new HTTP controller."""
    if not name.endswith("Controller"):
        name = name + "Controller"
    dest = Path.cwd() / "app" / "Http" / "Controllers" / f"{name}.py"
    dest.parent.mkdir(parents=True, exist_ok=True)
    if dest.exists():
        console.print(f"[yellow]Controller already exists:[/] {dest}")
        raise typer.Exit(1)
    tpl = RESOURCE_TEMPLATE if resource else TEMPLATE
    dest.write_text(tpl.format(name=name))
    console.print(f"[green]Controller created:[/] {dest}")
