"""REST API routes for {{ model_name }}.

⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
Extend this router in api/rest/{{ snake_name }}.py
"""

from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Query, status

from .deps import DbSession, Pagination, Sorting
from {{ package_name }}.schemas.{{ snake_name }} import (
    {{ model_name }}Create,
    {{ model_name }}Read,
    {{ model_name }}Update,
    {{ model_name }}Filter,
)
from {{ package_name }}.schemas.base import PaginatedResponse
from {{ package_name }}.services.{{ snake_name }} import {{ model_name }}Service

router = APIRouter(prefix="/{{ kebab_name }}", tags={{ tags }})

{% if ops_list %}

@router.get(
    "",
    response_model=PaginatedResponse[{{ model_name }}Read],
    summary="List {{ plural_name }}",
)
async def list_{{ plural_name }}(
    db: DbSession,
    pagination: Pagination,
    sorting: Sorting,
    include_deleted: Annotated[bool, Query(description="Include soft-deleted records")] = False,
) -> PaginatedResponse[{{ model_name }}Read]:
    """List {{ plural_name }} with pagination and filtering."""
    service = {{ model_name }}Service(db)

    items = await service.list(
        skip=pagination.skip,
        limit=pagination.limit,
        sort_by=sorting.sort_by,
        sort_order=sorting.sort_order,
        include_deleted=include_deleted,
    )

    total = await service.count(include_deleted=include_deleted)
    pages = (total + pagination.page_size - 1) // pagination.page_size

    return PaginatedResponse(
        items=[{{ model_name }}Read.model_validate(item) for item in items],
        total=total,
        page=pagination.page,
        page_size=pagination.page_size,
        pages=pages,
    )

{% endif %}
{% if ops_read %}

@router.get(
    "/{id}",
    response_model={{ model_name }}Read,
    summary="Get {{ snake_name }}",
)
async def get_{{ snake_name }}(
    db: DbSession,
    id: int,
) -> {{ model_name }}Read:
    """Get a {{ snake_name }} by ID."""
    service = {{ model_name }}Service(db)

    result = await service.get(id)
    if result is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="{{ model_name }} not found",
        )

    return {{ model_name }}Read.model_validate(result)

{% endif %}
{% if ops_create %}

@router.post(
    "",
    response_model={{ model_name }}Read,
    status_code=status.HTTP_201_CREATED,
    summary="Create {{ snake_name }}",
)
async def create_{{ snake_name }}(
    db: DbSession,
    data: {{ model_name }}Create,
) -> {{ model_name }}Read:
    """Create a new {{ snake_name }}."""
    service = {{ model_name }}Service(db)

    result = await service.create(data=data)
{% for rel in m2m_relationships %}
    # Handle {{ rel.name }} M2M relationship
    {{ rel.name }}_ids = getattr(data, "{{ rel.name }}Ids", None)
    if {{ rel.name }}_ids is not None:
        result = await service.set_{{ rel.name }}(result.id, {{ rel.name }}_ids)
{% endfor %}
    return {{ model_name }}Read.model_validate(result)

{% endif %}
{% if ops_update %}

@router.patch(
    "/{id}",
    response_model={{ model_name }}Read,
    summary="Update {{ snake_name }}",
)
async def update_{{ snake_name }}(
    db: DbSession,
    id: int,
    data: {{ model_name }}Update,
) -> {{ model_name }}Read:
    """Update a {{ snake_name }}."""
    service = {{ model_name }}Service(db)

    result = await service.update(id=id, data=data)
    if result is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="{{ model_name }} not found",
        )
{% for rel in m2m_relationships %}
    # Handle {{ rel.name }} M2M relationship
    {{ rel.name }}_ids = getattr(data, "{{ rel.name }}Ids", None)
    if {{ rel.name }}_ids is not None:
        result = await service.set_{{ rel.name }}(id, {{ rel.name }}_ids)
{% endfor %}

    return {{ model_name }}Read.model_validate(result)

{% endif %}
{% if ops_delete %}

@router.delete(
    "/{id}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="Delete {{ snake_name }}",
)
async def delete_{{ snake_name }}(
    db: DbSession,
    id: int,
    hard: Annotated[bool, Query(description="Permanently delete")] = False,
) -> None:
    """Delete a {{ snake_name }}."""
    service = {{ model_name }}Service(db)

    success = await service.delete(id=id, soft=not hard and {{ soft_delete }})
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="{{ model_name }} not found",
        )

{% endif %}
{% if ops_create %}

@router.post(
    "/bulk",
    response_model=list[{{ model_name }}Read],
    status_code=status.HTTP_201_CREATED,
    summary="Bulk create {{ plural_name }}",
)
async def bulk_create_{{ plural_name }}(
    db: DbSession,
    data: list[{{ model_name }}Create],
) -> list[{{ model_name }}Read]:
    """Create multiple {{ plural_name }} in a single request."""
    service = {{ model_name }}Service(db)

    results = await service.create_many(data=data)
    return [{{ model_name }}Read.model_validate(item) for item in results]

{% endif %}
{% if ops_update %}

@router.patch(
    "/bulk",
    summary="Bulk update {{ plural_name }}",
)
async def bulk_update_{{ plural_name }}(
    db: DbSession,
    ids: Annotated[list[int], Query(description="IDs to update")],
    data: {{ model_name }}Update,
) -> dict[str, int]:
    """Update multiple {{ plural_name }} with the same data."""
    service = {{ model_name }}Service(db)

    count = await service.update_many(ids=ids, data=data)
    return {"updated": count}

{% endif %}
{% if ops_delete %}

@router.delete(
    "/bulk",
    summary="Bulk delete {{ plural_name }}",
)
async def bulk_delete_{{ plural_name }}(
    db: DbSession,
    ids: Annotated[list[int], Query(description="IDs to delete")],
    hard: Annotated[bool, Query(description="Permanently delete")] = False,
) -> dict[str, int]:
    """Delete multiple {{ plural_name }}."""
    service = {{ model_name }}Service(db)

    count = await service.delete_many(ids=ids, soft=not hard and {{ soft_delete }})
    return {"deleted": count}

{% endif %}

__all__ = ["router"]
