import logging

from pydantic import BaseModel

from .rest_client import RestClient
from .models import get_path_from_item, get_path_from_type, Resource

logger = logging.getLogger(__name__)


class Paginated(BaseModel, frozen=True):

    count: int = 0
    next: str | None = None
    previous: str | None = None
    results: list[Resource] = []


class PortalClient(RestClient):

    def get_items(self, item_t, page: int = 1) -> Paginated:
        ret_json = self.get(get_path_from_type(item_t))
        if ret_json:
            return Paginated(
                count=ret_json["count"],
                next=ret_json["next"],
                previous=ret_json["previous"],
                results=[item_t(**item) for item in ret_json["results"]],
            )
        else:
            return Paginated()

    def create_item(self, resource: Resource) -> Resource:
        create_json = self.post(
            get_path_from_item(resource), resource.model_dump(mode="json")
        )
        return type(resource)(**create_json)

    def delete_item(self, resource: Resource):
        self.delete(f"{get_path_from_item(resource)}/{resource.id}/")
