"""GraphQL queries for {{ model_name }}.

⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
"""

from __future__ import annotations

from typing import Any

import strawberry
from strawberry.types import Info

from ..context import Context
from ..pagination import Connection, OffsetPaginationInput, paginate_results
from ..types.{{ snake_name }} import {{ model_name }}Type, {{ snake_name }}_from_model
from ..filters.{{ snake_name }} import {{ model_name }}WhereInput
from {{ package_name }}.services.{{ snake_name }} import {{ model_name }}Service
from {{ package_name }}.schemas.{{ snake_name }} import {{ model_name }}Filter


@strawberry.type
class {{ model_name }}Queries:
    """GraphQL queries for {{ model_name }}."""

    @strawberry.field(description="Get a single {{ model_name }} by ID")
    async def {{ camel_name }}(
        self,
        info: Info[Context, None],
        id: int,
    ) -> {{ model_name }}Type | None:
        """Get a {{ model_name }} by ID."""
        service = {{ model_name }}Service(info.context.db)
        result = await service.get(id)
        if result is None:
            return None
        return {{ snake_name }}_from_model(result)

    @strawberry.field(description="List {{ plural_name }} with filtering and pagination")
    async def {{ camel_plural }}(
        self,
        info: Info[Context, None],
        where: {{ model_name }}WhereInput | None = None,
        pagination: OffsetPaginationInput | None = None,
    ) -> Connection[{{ model_name }}Type]:
        """List {{ plural_name }}."""
        service = {{ model_name }}Service(info.context.db)

        page = pagination.page if pagination else 1
        page_size = pagination.page_size if pagination else 20
        skip = (page - 1) * page_size

        # Convert GraphQL where input to service filter
        filters = _convert_where_to_filter(where) if where else None

        items = await service.list(skip=skip, limit=page_size, filters=filters)
        total = await service.count_filtered(filters=filters)

        typed_items = [{{ snake_name }}_from_model(item) for item in items]
        return paginate_results(typed_items, total, page, page_size)


def _convert_where_to_filter(where: {{ model_name }}WhereInput) -> {{ model_name }}Filter:
    """Convert GraphQL where input to Pydantic filter schema."""
    filter_dict: dict[str, Any] = {}

    # Handle ID filter
    if where.id is not None:
        _apply_int_filter(filter_dict, "id", where.id)
{% for rel in relationships %}

    # Handle {{ rel.name }} relationship filter
    if where.{{ rel.camel_name }} is not None:
        {{ rel.name }}_filter = where.{{ rel.camel_name }}
        if {{ rel.name }}_filter.some is not None and {{ rel.name }}_filter.some.id is not None:
            if {{ rel.name }}_filter.some.id.eq is not None:
                filter_dict["{{ rel.name }}_id"] = {{ rel.name }}_filter.some.id.eq
            elif {{ rel.name }}_filter.some.id.in_ is not None:
                filter_dict["{{ rel.name }}_ids"] = {{ rel.name }}_filter.some.id.in_
{% endfor %}

    return {{ model_name }}Filter(**filter_dict)


def _apply_int_filter(filter_dict: dict[str, Any], field_name: str, filter_input: Any) -> None:
    """Apply an integer filter to the filter dictionary."""
    if filter_input.eq is not None:
        filter_dict[field_name] = filter_input.eq
    if filter_input.ne is not None:
        filter_dict[f"{field_name}_ne"] = filter_input.ne
    if filter_input.gt is not None:
        filter_dict[f"{field_name}_gt"] = filter_input.gt
    if filter_input.gte is not None:
        filter_dict[f"{field_name}_gte"] = filter_input.gte
    if filter_input.lt is not None:
        filter_dict[f"{field_name}_lt"] = filter_input.lt
    if filter_input.lte is not None:
        filter_dict[f"{field_name}_lte"] = filter_input.lte
    if filter_input.in_ is not None:
        filter_dict[f"{field_name}_in"] = filter_input.in_


__all__ = ["{{ model_name }}Queries"]
