from __future__ import annotations

from typing import Any

from app.repositories.directus.client import DirectusClient


class DirectusCollectionRepository:
    """Base repository for content-like resources stored in Directus.

    Subclasses only need to set `collection_name`.
    This keeps collection access consistent and review-friendly.
    """

    collection_name: str = ""
    default_fields: list[str] | None = None

    def __init__(self, client: DirectusClient | None = None) -> None:
        self.client = client or DirectusClient()

    async def list(
        self,
        params: dict[str, Any] | None = None,
        access_token: str | None = None,
    ) -> list[dict[str, Any]]:
        merged_params = self._merge_fields(params)
        return await self.client.list_items(
            self.collection_name,
            params=merged_params,
            access_token=access_token,
        )

    async def get(
        self,
        item_id: str,
        params: dict[str, Any] | None = None,
        access_token: str | None = None,
    ) -> dict[str, Any] | None:
        merged_params = self._merge_fields(params)
        return await self.client.get_item(
            self.collection_name,
            item_id=item_id,
            params=merged_params,
            access_token=access_token,
        )

    async def create(
        self,
        data: dict[str, Any],
        access_token: str | None = None,
    ) -> dict[str, Any]:
        return await self.client.create_item(
            self.collection_name,
            data=data,
            access_token=access_token,
        )

    async def update(
        self,
        item_id: str,
        data: dict[str, Any],
        access_token: str | None = None,
    ) -> dict[str, Any]:
        return await self.client.update_item(
            self.collection_name,
            item_id=item_id,
            data=data,
            access_token=access_token,
        )

    async def delete(self, item_id: str, access_token: str | None = None) -> None:
        await self.client.delete_item(
            self.collection_name,
            item_id=item_id,
            access_token=access_token,
        )

    def _merge_fields(self, params: dict[str, Any] | None) -> dict[str, Any] | None:
        if not self.default_fields:
            return params

        merged = dict(params or {})
        merged.setdefault("fields", ",".join(self.default_fields))
        return merged
