from __future__ import annotations

from uuid import UUID

from .base import SubclientBase
from ..schemas import EventResponse


class EventsClient(SubclientBase):

    async def list_events(
        self,
        event_types: list[str] | None = None,
        limit: int | None = None,
        offset: int | None = None,
    ) -> list[EventResponse]:
        headers: dict[str, str] = {}
        if event_types:
            headers["event-types"] = ",".join(event_types)
        if limit is not None:
            headers["limit"] = str(limit)
        if offset is not None:
            headers["offset"] = str(offset)

        response = await self._client.get_with_headers(
            self._client.path("/events"),
            headers=headers or None,
        )
        return self._client.parse_list(response, EventResponse)

    async def list_aggregate_events(
        self,
        aggregate_id: UUID,
        version: str | None = None,
    ) -> list[EventResponse]:
        params = {"version": version} if version is not None else None
        response = await self._client.get(
            self._client.path(f"/events/aggregate/{aggregate_id}/history"),
            params=params,
        )
        return self._client.parse_list(response, EventResponse)

    async def query_item_events(
        self,
        item_id: UUID,
        version: str | None = None,
    ) -> list[EventResponse]:
        params = {"version": version} if version is not None else None
        response = await self._client.get(
            self._client.path(f"/events/items/{item_id}"),
            params=params,
        )
        return self._client.parse_list(response, EventResponse)

    async def query_item_last_event(
        self,
        item_id: UUID,
        version: str | None = None,
    ) -> EventResponse:
        params = {"version": version} if version is not None else None
        response = await self._client.get(
            self._client.path(f"/events/items/{item_id}/last"),
            params=params,
        )
        return self._client.parse(response, EventResponse)

    async def query_item_last_n_events(
        self,
        item_id: UUID,
        n: int,
        version: str | None = None,
    ) -> list[EventResponse]:
        params = {"version": version} if version is not None else None
        response = await self._client.get(
            self._client.path(f"/events/items/{item_id}/last/{n}"),
            params=params,
        )
        return self._client.parse_list(response, EventResponse)
