from typing import Any, Dict, Optional


class Payins:
    """Create and manage payins (payment requests)."""

    def __init__(self, client):
        self._client = client

    def create(
        self,
        amount: str,
        external_ref: str = None,
        expires_in_seconds: int = None,
        metadata: Dict[str, Any] = None,
        success_url: str = None,
        cancel_url: str = None,
        sandbox: bool = False,
    ) -> dict:
        """
        Create a new payin (payment request).

        Args:
            amount: Amount in USDT (minimum 20 USDT), e.g. "100"
            external_ref: Your internal order/reference ID
            expires_in_seconds: Custom expiry in seconds (minimum 900)
            metadata: Arbitrary metadata stored with the payin
            success_url: URL to redirect customer after confirmed payment
            cancel_url: URL to redirect customer if payment expires
            sandbox: Set to True for test mode

        Returns:
            Dict with transactionId, address, paymentUrl, qrCodeUrl, amount, etc.
        """
        body = {"amount": amount}
        if external_ref is not None:
            body["externalRef"] = external_ref
        if expires_in_seconds is not None:
            body["expiresInSeconds"] = expires_in_seconds
        if metadata is not None:
            body["metadata"] = metadata
        if success_url is not None:
            body["successUrl"] = success_url
        if cancel_url is not None:
            body["cancelUrl"] = cancel_url

        params = {"sandbox": "true"} if sandbox else None
        res = self._client.post("/payin", json=body, params=params)
        return res["data"]

    def get(self, payin_id: str) -> dict:
        """
        Get a payin by ID.

        Returns:
            Dict with id, address, amount, amountReceived, status, paymentUrl, etc.
        """
        res = self._client.get(f"/payin/{payin_id}")
        return res["data"]

    def list(
        self,
        page: int = None,
        limit: int = None,
        status: str = None,
    ) -> dict:
        """
        List payins with optional filters.

        Returns:
            Dict with "items" (list) and "total" (int).
        """
        res = self._client.get("/payin", params={"page": page, "limit": limit, "status": status})
        return res["data"]

    def simulate(self, payin_id: str) -> dict:
        """Simulate payin confirmation (sandbox only)."""
        res = self._client.post(f"/sandbox/payin/{payin_id}/simulate")
        return res["data"]
