"""Datastores resource."""

from __future__ import annotations

from .._client import AplikuClient
from .._models import Datastore, DatastoreCreate, DatastoreLogsResponse, PaginatedResponse


class DatastoresResource:
    def __init__(self, client: AplikuClient) -> None:
        self._client = client

    def _base(self, team: str, app_id: int) -> str:
        return f"/api/team/{team}/applications/{app_id}/datastores"

    def list(
        self, team: str, app_id: int, *, page: int = 1, page_size: int = 20
    ) -> PaginatedResponse[Datastore]:
        """List datastores for an app."""
        return self._client.paginate(
            f"{self._base(team, app_id)}/",
            params={"page": page, "page_size": page_size},
            response_type=Datastore,
        )

    def get(self, team: str, app_id: int, ds_id: int) -> Datastore:
        """Get a single datastore."""
        data = self._client.get(f"{self._base(team, app_id)}/{ds_id}/")
        return Datastore.model_validate(data)

    def create(self, team: str, app_id: int, name: str, engine: str, **kwargs: object) -> Datastore:
        """Create a datastore."""
        body = DatastoreCreate(name=name, engine=engine, **kwargs)  # type: ignore[arg-type]
        data = self._client.post(
            f"{self._base(team, app_id)}/",
            json=body.model_dump(exclude_none=True),
        )
        return Datastore.model_validate(data)

    def delete(self, team: str, app_id: int, ds_id: int) -> None:
        """Delete a datastore."""
        self._client.delete(f"{self._base(team, app_id)}/{ds_id}/")

    def start(self, team: str, app_id: int, ds_id: int) -> Datastore:
        """Start a datastore."""
        data = self._client.patch(f"{self._base(team, app_id)}/{ds_id}/start")
        return Datastore.model_validate(data)

    def stop(self, team: str, app_id: int, ds_id: int) -> Datastore:
        """Stop a datastore."""
        data = self._client.patch(f"{self._base(team, app_id)}/{ds_id}/stop")
        return Datastore.model_validate(data)

    def restart(self, team: str, app_id: int, ds_id: int) -> Datastore:
        """Restart a datastore."""
        data = self._client.patch(f"{self._base(team, app_id)}/{ds_id}/restart")
        return Datastore.model_validate(data)

    def logs(self, team: str, app_id: int, ds_id: int) -> DatastoreLogsResponse:
        """Get logs for a datastore."""
        data = self._client.get(f"{self._base(team, app_id)}/{ds_id}/logs/")
        return DatastoreLogsResponse.model_validate(data)
