"""
Guest CRUD operations
"""

from typing import Dict, Any, Optional
from .base import UserManagerBase
from ..models import Guest, TallyfyError


class GuestOperations(UserManagerBase):
    """Handles guest CRUD operations"""

    def create_guest(self, org_id: str, email: str, first_name: str,
                     last_name: str, phone: Optional[str] = None,
                     company_name: Optional[str] = None) -> Guest:
        """
        Create a new guest in the organization.

        Args:
            org_id: Organization ID
            email: Guest email address (required)
            first_name: Guest first name (required)
            last_name: Guest last name (required)
            phone: Guest phone number
            company_name: Guest company name

        Returns:
            Created Guest object

        Raises:
            TallyfyError: If the request fails
            ValueError: If required parameters are missing or invalid
        """
        self._validate_org_id(org_id)
        self._validate_email(email)
        self._validate_name(first_name, "First name")
        self._validate_name(last_name, "Last name")

        try:
            endpoint = f"organizations/{org_id}/guests"
            body: Dict[str, Any] = {
                "email": email,
                "first_name": first_name.strip(),
                "last_name": last_name.strip()
            }

            if phone is not None:
                body["phone"] = phone
            if company_name is not None:
                body["company_name"] = company_name

            response_data = self.sdk._make_request('POST', endpoint, data=body)

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

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

            raise TallyfyError("Unexpected response format for create_guest")

        except TallyfyError:
            raise
        except Exception as e:
            self._handle_api_error(e, "create guest", org_id=org_id, email=email)

    def get_guest(self, org_id: str, email: str) -> Guest:
        """
        Get a single guest by email.

        Args:
            org_id: Organization ID
            email: Guest email address

        Returns:
            Guest object

        Raises:
            TallyfyError: If the request fails
        """
        self._validate_org_id(org_id)
        self._validate_email(email)

        try:
            endpoint = f"organizations/{org_id}/guests/{email}"
            response_data = self.sdk._make_request('GET', endpoint)

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

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

            raise TallyfyError("Unexpected response format for get_guest")

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

    def update_guest(self, org_id: str, email: str,
                     first_name: Optional[str] = None,
                     last_name: Optional[str] = None,
                     phone: Optional[str] = None,
                     company_name: Optional[str] = None) -> Guest:
        """
        Update a guest's profile.

        Args:
            org_id: Organization ID
            email: Guest email address
            first_name: New first name
            last_name: New last name
            phone: New phone number
            company_name: New company name

        Returns:
            Updated Guest object

        Raises:
            TallyfyError: If the request fails
        """
        self._validate_org_id(org_id)
        self._validate_email(email)

        try:
            endpoint = f"organizations/{org_id}/guests/{email}"
            body: Dict[str, Any] = {}

            if first_name is not None:
                body["first_name"] = first_name.strip()
            if last_name is not None:
                body["last_name"] = last_name.strip()
            if phone is not None:
                body["phone"] = phone
            if company_name is not None:
                body["company_name"] = company_name

            if not body:
                raise ValueError("At least one field must be provided for update")

            response_data = self.sdk._make_request('PUT', endpoint, data=body)

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

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

            raise TallyfyError("Unexpected response format for update_guest")

        except TallyfyError:
            raise
        except Exception as e:
            self._handle_api_error(e, "update guest", org_id=org_id, email=email)

    def disable_guest(self, org_id: str, email: str) -> bool:
        """
        Disable a guest in the organization.

        Args:
            org_id: Organization ID
            email: Guest email address

        Returns:
            True if disabled successfully

        Raises:
            TallyfyError: If the request fails
        """
        self._validate_org_id(org_id)
        self._validate_email(email)

        try:
            endpoint = f"organizations/{org_id}/guests/{email}/disable"
            self.sdk._make_request('DELETE', endpoint)
            return True

        except TallyfyError:
            raise
        except Exception as e:
            self._handle_api_error(e, "disable guest", org_id=org_id, email=email)

    def enable_guest(self, org_id: str, email: str) -> bool:
        """
        Re-enable a previously disabled guest.

        Args:
            org_id: Organization ID
            email: Guest email address

        Returns:
            True if enabled successfully

        Raises:
            TallyfyError: If the request fails
        """
        self._validate_org_id(org_id)
        self._validate_email(email)

        try:
            endpoint = f"organizations/{org_id}/guests/{email}/enable"
            self.sdk._make_request('PUT', endpoint)
            return True

        except TallyfyError:
            raise
        except Exception as e:
            self._handle_api_error(e, "enable guest", org_id=org_id, email=email)
