"""Resource ``subscriptions`` — cobranças recorrentes."""

from __future__ import annotations

from collections.abc import Mapping
from typing import Any

from ..models import CreateSubscriptionParams, Subscription
from ._base import AsyncResource, SyncResource, coerce_params, list_payload

SubscriptionInput = CreateSubscriptionParams | Mapping[str, Any]


class SubscriptionsResource(SyncResource):
    def create(self, params: SubscriptionInput) -> Subscription:
        """Cria um checkout de assinatura. O produto precisa ter `cycle` definido."""
        payload = coerce_params(params, CreateSubscriptionParams).to_payload()
        data = self._post("/subscriptions/create", json=payload)
        return Subscription.model_validate(data)

    def list(self) -> list[Subscription]:
        data = self._get("/subscriptions/list")
        return [Subscription.model_validate(item) for item in list_payload(data)]

    def cancel(self, id: str) -> Subscription:
        """Cancela uma assinatura ativa."""
        data = self._post("/subscriptions/cancel", json={"id": id})
        return Subscription.model_validate(data)


class AsyncSubscriptionsResource(AsyncResource):
    async def create(self, params: SubscriptionInput) -> Subscription:
        payload = coerce_params(params, CreateSubscriptionParams).to_payload()
        data = await self._post("/subscriptions/create", json=payload)
        return Subscription.model_validate(data)

    async def list(self) -> list[Subscription]:
        data = await self._get("/subscriptions/list")
        return [Subscription.model_validate(item) for item in list_payload(data)]

    async def cancel(self, id: str) -> Subscription:
        data = await self._post("/subscriptions/cancel", json={"id": id})
        return Subscription.model_validate(data)


__all__ = ["AsyncSubscriptionsResource", "SubscriptionsResource"]
