"""Slices Project API."""

from datetime import datetime

from httpx import Client, HTTPError
from msgspec import Struct
from msgspec.json import Decoder as JsonDecoder

from slices_clientlib_core.base.exceptions import from_httpx_exception


class User(Struct):
    """User."""

    affiliation: str
    created_at: datetime  # doesn't always have a timezone
    email: str
    first_name: str
    id: str
    last_name: str
    organisation: str
    preferred_username: str


_user_decoder = JsonDecoder(User)


class UserClient:
    """Project Client."""

    API_BASE_PATH = "/apis/user.slices-ri.eu/v1/users/"

    def __init__(self, client: Client) -> None:
        """Create User Client."""
        self._client = client

        assert client.base_url is not None, "Expected base_url to be set"

    def get(self, id: str) -> User:
        """Get project by ID."""
        response = self._client.get(f"{self.API_BASE_PATH}{id}")

        try:
            response.raise_for_status()
            return _user_decoder.decode(response.content)
        except HTTPError as err:
            raise from_httpx_exception(err) from err
