"""Workspace resource for the Daly Energy SDK.

Workspaces are the top-level organizational unit. All resources (locations,
projects, modules, etc.) belong to a workspace and are isolated via
Row-Level Security.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from dalysdk.client import DalyClient


class WorkspaceResource:
    """Interact with the ``/workspaces`` endpoints.

    Usage::

        workspaces = client.workspaces.list()
        workspace = client.workspaces.get(1)
        updated = client.workspaces.update(1, {"identifier": "new-name"})
        client.workspaces.delete(1)

        # Admin: create a new workspace
        result = client.workspaces.create({"identifier": "acme-solar"})

        # List users in a workspace
        users = client.workspaces.list_users(1)

        # Get workspace settings
        settings = client.workspaces.get_settings(1)
    """

    def __init__(self, client: DalyClient):
        self._client = client

    def list(self) -> list[dict]:
        """List workspaces accessible to the current user.

        Currently returns only the authenticated workspace.

        Returns:
            List of workspace dicts.
        """
        return self._client._request("GET", "/workspaces")

    def get(self, workspace_id: int) -> dict:
        """Get a workspace by ID.

        Args:
            workspace_id: Workspace ID.

        Returns:
            Workspace dict.

        Raises:
            NotFoundError: If the workspace does not exist.
        """
        return self._client._request("GET", f"/workspaces/{workspace_id}")

    def create(self, data: dict) -> dict:
        """Create a new workspace.

        This is a system-level operation. Returns the plaintext API key
        for the new workspace -- this is the only time the key is visible.

        Args:
            data: Must include ``identifier`` (workspace name/slug).

        Returns:
            Dict with ``workspace_id``, ``identifier``, and ``api_key``.
        """
        return self._client._request("POST", "/workspaces", json=data)

    def update(self, workspace_id: int, data: dict) -> dict:
        """Update workspace metadata.

        Can only update the currently authenticated workspace.

        Args:
            workspace_id: Workspace ID.
            data: Fields to update (e.g. ``{"identifier": "new-name"}``).

        Returns:
            Updated workspace dict.

        Raises:
            ForbiddenError: If attempting to update a different workspace.
            NotFoundError: If the workspace does not exist.
        """
        return self._client._request("PUT", f"/workspaces/{workspace_id}", json=data)

    def delete(self, workspace_id: int) -> dict:
        """Delete a workspace.

        Can only delete the currently authenticated workspace.

        Args:
            workspace_id: Workspace ID.

        Returns:
            Confirmation dict (``{"deleted": True}``).

        Raises:
            ForbiddenError: If attempting to delete a different workspace.
            NotFoundError: If the workspace does not exist.
        """
        return self._client._request("DELETE", f"/workspaces/{workspace_id}")

    def list_users(self, workspace_id: int) -> list[dict]:
        """List users in a workspace.

        Args:
            workspace_id: Workspace ID.

        Returns:
            List of user dicts.
        """
        return self._client._request("GET", f"/workspaces/{workspace_id}/users")

    def get_settings(self, workspace_id: int) -> dict:
        """Get workspace settings.

        Args:
            workspace_id: Workspace ID.

        Returns:
            Workspace settings dict.

        Raises:
            NotFoundError: If settings are not found.
        """
        return self._client._request("GET", f"/workspaces/{workspace_id}/settings")
