"""Campaign management resource."""

from __future__ import annotations

from typing import TYPE_CHECKING

from resletter.types import Campaign, CampaignStatus

if TYPE_CHECKING:
    from resletter.client import Resletter


class CampaignsResource:
    """Campaign management resource.

    Example:
        >>> # List campaigns
        >>> campaigns = client.campaigns.list(status="active")
        >>> for campaign in campaigns:
        ...     print(campaign["name"])

        >>> # Create a campaign
        >>> campaign = client.campaigns.create(
        ...     name="Product Launch Campaign",
        ...     description="Campaign for new product announcement",
        ...     subscriber_group_ids=["group-1", "group-2"],
        ... )
    """

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

    def list(self, *, status: CampaignStatus | None = None) -> list[Campaign]:
        """List campaigns with optional filtering.

        Args:
            status: Filter by status ('active', 'paused', 'completed', 'archived').

        Returns:
            List of campaigns.

        Example:
            >>> active_campaigns = client.campaigns.list(status="active")
        """
        params = {"status": status} if status else None
        return self._client._request("GET", "/campaigns", params=params)

    def get(self, campaign_id: str) -> Campaign:
        """Get a campaign by ID.

        Args:
            campaign_id: The campaign's unique ID.

        Returns:
            Campaign data.

        Raises:
            ResletterError: If campaign not found (404).
        """
        return self._client._request("GET", f"/campaigns/{campaign_id}")

    def create(
        self,
        *,
        name: str,
        description: str | None = None,
        subscriber_group_ids: list[str] | None = None,
    ) -> Campaign:
        """Create a new campaign.

        Args:
            name: Campaign name (required).
            description: Campaign description.
            subscriber_group_ids: List of group IDs to target.

        Returns:
            Created campaign data.

        Example:
            >>> campaign = client.campaigns.create(
            ...     name="Product Launch Campaign",
            ...     description="Campaign for new product announcement",
            ...     subscriber_group_ids=["group-1", "group-2"],
            ... )
        """
        body: dict[str, str | list[str]] = {"name": name}
        if description is not None:
            body["description"] = description
        if subscriber_group_ids is not None:
            body["subscriberGroupIds"] = subscriber_group_ids

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

    def update(
        self,
        campaign_id: str,
        *,
        name: str | None = None,
        description: str | None = None,
        status: CampaignStatus | None = None,
        subscriber_group_ids: list[str] | None = None,
    ) -> Campaign:
        """Update a campaign.

        Args:
            campaign_id: The campaign's unique ID.
            name: New name.
            description: New description.
            status: New status ('active', 'paused', 'completed', 'archived').
            subscriber_group_ids: New list of group IDs to target.

        Returns:
            Updated campaign data.
        """
        body: dict[str, str | list[str]] = {}
        if name is not None:
            body["name"] = name
        if description is not None:
            body["description"] = description
        if status is not None:
            body["status"] = status
        if subscriber_group_ids is not None:
            body["subscriberGroupIds"] = subscriber_group_ids

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

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

        Args:
            campaign_id: The campaign's unique ID.

        Returns:
            Dictionary with 'message' key.

        Note:
            Cannot delete campaigns that contain newsletters. Archive them instead.
        """
        return self._client._request("DELETE", f"/campaigns/{campaign_id}")
