"""Organizations resource client for V1."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from concentriq.client import ConcentriqClient


class Organizations:
    """Client for Organization resources (/api/organizations)."""

    def __init__(self, client: "ConcentriqClient"):
        """Initialize with client instance.

        Args:
            client: ConcentriqClient instance
        """
        self._client = client
        self._base_path = "/api/organizations"

    def list(self) -> list[dict[str, Any]]:
        """List all organizations.

        Note: This endpoint requires admin privileges.

        Returns:
            List of organization dictionaries

        Raises:
            AuthenticationError: If not authenticated or not admin

        Example:
            organizations = client.v1.organizations.list()
            for org in organizations:
                print(f"{org['name']}: {org['billingEmail']}")
        """
        response = self._client._request("GET", self._base_path)
        data = response.json()

        # V1 API returns data in envelope format with 'organizations' key
        return data.get("data", {}).get("organizations", [])

    def get(self, id: int) -> dict[str, Any]:
        """Get a single organization by ID.

        Args:
            id: Organization ID

        Returns:
            Organization dictionary

        Raises:
            AuthenticationError: If not authenticated
            NotFoundError: If organization not found

        Example:
            org = client.v1.organizations.get(123)
            print(f"Organization: {org['name']}")
        """
        response = self._client._request("GET", f"{self._base_path}/{id}")
        data = response.json()

        # V1 API returns data with 'organization' key
        return data.get("data", {}).get("organization", {})

    def create(self, data: dict[str, Any]) -> dict[str, Any]:
        """Create a new organization.

        Note: This endpoint requires admin privileges.

        Args:
            data: Organization data (name, billingEmail)

        Returns:
            Created organization dictionary with id

        Raises:
            AuthenticationError: If not authenticated or not admin
            ValidationError: If data is invalid

        Example:
            org = client.v1.organizations.create({
                "name": "New Organization",
                "billingEmail": "billing@neworg.com"
            })
            print(f"Created organization {org['id']}")
        """
        response = self._client._request("POST", self._base_path, json=data)
        result = response.json()

        # V1 API returns data in envelope format
        return result.get("data", {})
