"""Group management resource."""

from __future__ import annotations

from typing import TYPE_CHECKING

from resletter.types import (
    AddSubscribersToGroupResponse,
    RemoveSubscribersFromGroupResponse,
    SubscriberGroup,
)

if TYPE_CHECKING:
    from resletter.client import Resletter


class GroupsResource:
    """Group management resource.

    Example:
        >>> # List groups
        >>> groups = client.groups.list()
        >>> for group in groups:
        ...     print(f"{group['name']}: {group['subscriberCount']} subscribers")

        >>> # Create a group
        >>> group = client.groups.create(
        ...     name="Product Updates",
        ...     description="Subscribers interested in product news",
        ...     color="#3B82F6",
        ... )
    """

    def __init__(self, client: Resletter) -> None:
        self._client = client

    def list(self) -> list[SubscriberGroup]:
        """List all subscriber groups.

        Returns:
            List of groups with subscriber counts.
        """
        return self._client._request("GET", "/groups")

    def get(self, group_id: str) -> SubscriberGroup:
        """Get a group by ID.

        Args:
            group_id: The group's unique ID.

        Returns:
            Group data.

        Raises:
            ResletterError: If group not found (404).
        """
        return self._client._request("GET", f"/groups/{group_id}")

    def create(
        self,
        *,
        name: str,
        description: str | None = None,
        color: str | None = None,
    ) -> SubscriberGroup:
        """Create a new group.

        Args:
            name: Group name (required).
            description: Group description.
            color: Hex color code (e.g., '#3B82F6').

        Returns:
            Created group data.

        Example:
            >>> group = client.groups.create(
            ...     name="Product Updates",
            ...     description="Subscribers interested in product news",
            ...     color="#3B82F6",
            ... )
        """
        body: dict[str, str] = {"name": name}
        if description is not None:
            body["description"] = description
        if color is not None:
            body["color"] = color

        return self._client._request("POST", "/groups", json=body)

    def update(
        self,
        group_id: str,
        *,
        name: str | None = None,
        description: str | None = None,
        color: str | None = None,
    ) -> SubscriberGroup:
        """Update a group.

        Args:
            group_id: The group's unique ID.
            name: New name.
            description: New description.
            color: New hex color code.

        Returns:
            Updated group data.
        """
        body: dict[str, str] = {}
        if name is not None:
            body["name"] = name
        if description is not None:
            body["description"] = description
        if color is not None:
            body["color"] = color

        return self._client._request("PATCH", f"/groups/{group_id}", json=body)

    def delete(self, group_id: str) -> dict[str, str]:
        """Delete a group.

        Args:
            group_id: The group's unique ID.

        Returns:
            Dictionary with 'message' key.

        Note:
            This does not delete subscribers in the group, only the group itself.
        """
        return self._client._request("DELETE", f"/groups/{group_id}")

    def add_subscribers(
        self,
        group_id: str,
        *,
        subscriber_ids: list[str],
    ) -> AddSubscribersToGroupResponse:
        """Add subscribers to a group.

        Args:
            group_id: The group's unique ID.
            subscriber_ids: List of subscriber IDs to add.

        Returns:
            Response with 'added' and 'alreadyInGroup' counts.

        Example:
            >>> result = client.groups.add_subscribers(
            ...     "group-id",
            ...     subscriber_ids=["sub-1", "sub-2"],
            ... )
            >>> print(f"Added {result['added']} subscribers")
        """
        body = {"subscriberIds": subscriber_ids}
        return self._client._request("POST", f"/groups/{group_id}/subscribers", json=body)

    def remove_subscribers(
        self,
        group_id: str,
        *,
        subscriber_ids: list[str],
    ) -> RemoveSubscribersFromGroupResponse:
        """Remove subscribers from a group.

        Args:
            group_id: The group's unique ID.
            subscriber_ids: List of subscriber IDs to remove.

        Returns:
            Response with 'removed' count.

        Example:
            >>> result = client.groups.remove_subscribers(
            ...     "group-id",
            ...     subscriber_ids=["sub-1"],
            ... )
            >>> print(f"Removed {result['removed']} subscribers")
        """
        body = {"subscriberIds": subscriber_ids}
        return self._client._request("DELETE", f"/groups/{group_id}/subscribers", json=body)
