"""
Subscriptions resource for the Jokoor SDK
"""

from typing import Optional, Dict, Any, Tuple

from ..types import Subscription, PaginatedResponse
from ..http_client import HTTPClient


class SubscriptionsResource:
    """Subscription operations"""

    def __init__(self, http_client: HTTPClient) -> None:
        self._http = http_client

    def create(
        self,
        *,
        customer_id: str,
        product_id: str,
        interval: str = "monthly",
        interval_count: int = 1,
    ) -> Tuple[Optional[Subscription], Optional[str]]:
        """Create a subscription"""
        data: Dict[str, Any] = {
            "customer_id": customer_id,
            "product_id": product_id,
            "interval": interval,
            "interval_count": interval_count,
        }

        response, error = self._http.post("/v1/pay/subscriptions", data)
        if error:
            return (None, str(error))
        return (response, None)  # type: ignore

    def get(self, subscription_id: str) -> Tuple[Optional[Subscription], Optional[str]]:
        """Get subscription details"""
        response, error = self._http.get(f"/v1/pay/subscriptions/{subscription_id}")
        if error:
            return (None, str(error))
        return (response, None)  # type: ignore

    def list(
        self, *, offset: int = 0, limit: int = 20, status: Optional[str] = None
    ) -> Tuple[Optional[PaginatedResponse], Optional[str]]:
        """List subscriptions"""
        params: Dict[str, Any] = {"offset": offset, "limit": limit}
        if status:
            params["status"] = status

        response, error = self._http.get("/v1/pay/subscriptions", params)
        if error:
            return (None, str(error))
        return (response, None)  # type: ignore

    def update(
        self,
        subscription_id: str,
        *,
        product_id: Optional[str] = None,
        interval: Optional[str] = None,
        interval_count: Optional[int] = None,
    ) -> Tuple[Optional[Subscription], Optional[str]]:
        """Update subscription settings"""
        data: Dict[str, Any] = {}
        if product_id is not None:
            data["product_id"] = product_id
        if interval is not None:
            data["interval"] = interval
        if interval_count is not None:
            data["interval_count"] = interval_count

        response, error = self._http.put(
            f"/v1/pay/subscriptions/{subscription_id}", data
        )
        if error:
            return (None, str(error))
        return (response, None)  # type: ignore

    def cancel(
        self, subscription_id: str, *, cancel_at_period_end: bool = False
    ) -> Tuple[Optional[Subscription], Optional[str]]:
        """Cancel a subscription"""
        data = {"cancel_at_period_end": cancel_at_period_end}
        response, error = self._http.post(
            f"/v1/pay/subscriptions/{subscription_id}/cancel", data
        )
        if error:
            return (None, str(error))
        return (response, None)  # type: ignore

    def list_invoices(
        self,
        subscription_id: str,
        *,
        offset: int = 0,
        limit: int = 20,
    ) -> Tuple[Optional[PaginatedResponse], Optional[str]]:
        """
        List all invoices generated by a subscription

        Args:
            subscription_id: Subscription ID
            offset: Number of items to skip
            limit: Maximum number of items to return

        Returns:
            Tuple of (PaginatedResponse, error) where error is None on success

        Example:
            ```python
            invoices, error = jokoor.subscriptions.list_invoices('sub_123', offset=0, limit=20)
            if error:
                print(f"Error: {error}")
            else:
                for invoice in invoices['items']:
                    print(f"Invoice: {invoice['invoice_number']}")
            ```
        """
        if not subscription_id:
            return (None, "Subscription ID is required")

        params: Dict[str, Any] = {"offset": offset, "limit": limit}

        response, error = self._http.get(
            f"/v1/pay/subscriptions/{subscription_id}/invoices", params
        )
        if error:
            return (None, str(error))
        return (response, None)  # type: ignore

    def trigger_processing(self) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
        """
        Manually trigger subscription processing

        Triggers processing of subscriptions that are due for billing.
        Primarily used for testing and administrative purposes.

        Returns:
            Tuple of (result dict, error) where error is None on success

        Example:
            ```python
            result, error = jokoor.subscriptions.trigger_processing()
            if error:
                print(f"Error: {error}")
            else:
                print(f"Processed {result['processed']} subscriptions")
            ```
        """
        response, error = self._http.post("/v1/pay/subscriptions/trigger-processing")
        if error:
            return (None, str(error))
        return (response, None)  # type: ignore
