"""
Organization retrieval operations
"""

from typing import Dict, Any, List, Optional
from .base import OrganizationManagerBase
from ..models import Organization, OrganizationsList, TallyfyError
from ..validation import validate_id


class OrganizationRetrieval(OrganizationManagerBase):
    """Handles organization retrieval operations"""

    def get_organization(self, org_id: str, with_: Optional[str] = None) -> Organization:
        """
        Get details of a single organization.

        Args:
            org_id: Organization ID
            with_: Comma-separated includes (e.g. 'subscription,billing_info')

        Returns:
            Organization object

        Raises:
            TallyfyError: If the request fails
        """
        validate_id(org_id, "Organization ID")

        try:
            endpoint = f"organizations/{org_id}"
            params: Dict[str, Any] = {}
            if with_ is not None:
                params['with'] = with_

            response_data = self.sdk._make_request('GET', endpoint, params=params)

            if isinstance(response_data, dict) and 'data' in response_data:
                data = response_data['data']
                if isinstance(data, dict):
                    return Organization.from_dict(data)

            if isinstance(response_data, dict):
                return Organization.from_dict(response_data)

            raise TallyfyError("Unexpected response format for get_organization")

        except TallyfyError:
            raise
        except Exception as e:
            self._handle_api_error(e, "get organization", org_id=org_id)

    def get_current_user_organizations(self, page: int = 1, per_page: int = 10) -> OrganizationsList:
        """
        Get all organizations the current member is a part of.

        Args:
            page: Page number (default: 1)
            per_page: Number of results per page (default: 10, max: 100)

        Returns:
            OrganizationsList object containing organizations and pagination metadata

        Raises:
            TallyfyError: If the request fails
        """
        try:
            endpoint = "me/organizations"
            params = self._build_query_params(page=page, per_page=min(per_page, 100))
            
            response_data = self.sdk._make_request('GET', endpoint, params=params)

            # Return the structured response with pagination
            return OrganizationsList.from_dict(response_data)

        except TallyfyError:
            raise
        except Exception as e:
            self._handle_api_error(e, "get my organizations", page=page, per_page=per_page)