"""Links service - URL shortening."""

from typing import Any, Dict, List, Optional
from sed_sh.services.base import BaseService


class LinksService(BaseService):
    """Service for managing shortened URLs.

    All methods may raise SedSHError or its subclasses on error.
    No automatic retries are performed - implement retry logic in your application if needed.
    No client-side validation is performed - validation errors come from the API.
    """

    def create(
        self, target_url: str, password: Optional[str] = None
    ) -> Dict[str, Any]:
        """Create a shortened URL.

        Args:
            target_url: The URL to shorten
            password: Optional password protection for the link

        Returns:
            Dict containing:
                - success (bool): Whether the operation succeeded
                - shortUrl (str): The shortened URL (e.g., "https://sed.sh/abc12")
                - code (str): The short code (e.g., "abc12")
                - targetUrl (str): The target URL
                - hasPassword (bool): Whether password protection is enabled
                - expiresAt (int): Unix timestamp when link expires
                - expiresIn (str): Human-readable expiration time

        Raises:
            InvalidRequestError: If target_url is invalid
            AuthenticationError: If API key is invalid
            RateLimitError: If rate limit is exceeded
            SedSHError: On other errors

        Example:
            >>> link = client.links.create("https://example.com")
            >>> print(link['shortUrl'])
            'https://sed.sh/abc12'

            >>> protected_link = client.links.create(
            ...     "https://example.com/secret",
            ...     password="secret123"
            ... )
        """
        payload: Dict[str, Any] = {"targetUrl": target_url}
        if password is not None:
            payload["password"] = password

        return self._request("POST", "/links", json=payload)

    def list(self) -> Dict[str, Any]:
        """List all links created with your API key.

        Returns:
            Dict containing:
                - success (bool): Whether the operation succeeded
                - links (list): List of link objects, each containing:
                    - code (str): The short code
                    - shortUrl (str): The shortened URL
                    - targetUrl (str): The target URL
                    - clicks (int): Number of clicks
                    - hasPassword (bool): Whether password protected
                    - expiresAt (int): Unix timestamp when link expires
                    - createdAt (int): Unix timestamp when link was created

        Raises:
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> links = client.links.list()
            >>> for link in links['links']:
            ...     print(f"{link['shortUrl']} -> {link['targetUrl']}")
        """
        return self._request("GET", "/links")

    def delete(self, code: str) -> Dict[str, Any]:
        """Delete a shortened link.

        Args:
            code: The short code of the link to delete (e.g., "abc12")

        Returns:
            Dict containing:
                - success (bool): Whether the operation succeeded
                - message (str): Confirmation message

        Raises:
            ResourceNotFoundError: If link code doesn't exist
            AuthenticationError: If API key is invalid or doesn't own this link
            SedSHError: On other errors

        Example:
            >>> result = client.links.delete("abc12")
            >>> print(result['message'])
            'Link deleted successfully'
        """
        return self._request("DELETE", f"/links/{code}")
