"""Products API endpoint mixin (for add-on purchases)."""

from typing import TYPE_CHECKING, Any

from growflow_billing.models.product import Price, Product, ProductCheckoutSession

if TYPE_CHECKING:
    from growflow_billing.client import GrowFlowBillingClient


class ProductsMixin:
    """Mixin for product-related API calls (add-ons, one-time purchases)."""

    async def get_products(
        self: "GrowFlowBillingClient",
        active: bool = True,
    ) -> list[Product]:
        """Get available products for purchase.

        Args:
            active: Filter by active status (default: True)

        Returns:
            List of Product objects

        Example:
            products = await client.get_products()
            for product in products:
                print(f"{product.name}: {product.default_price.amount_decimal}")
        """
        response = await self._request(
            "GET",
            "/products",
            params={"active": str(active).lower()},
        )

        if isinstance(response, list):
            return [Product(**p) for p in response]
        return [Product(**p) for p in response.get("items", response.get("data", []))]

    async def get_product(
        self: "GrowFlowBillingClient",
        product_id: str,
    ) -> Product:
        """Get a specific product by ID.

        Args:
            product_id: Product ID

        Returns:
            Product object

        Raises:
            NotFoundError: If product not found
        """
        response = await self._request("GET", f"/products/{product_id}")
        return Product(**response)

    async def create_product_checkout(
        self: "GrowFlowBillingClient",
        customer_external_id: str,
        price_id: str,
        success_url: str,
        cancel_url: str,
        quantity: int = 1,
    ) -> ProductCheckoutSession:
        """Create checkout session for a product purchase.

        Args:
            customer_external_id: Your internal customer ID
            price_id: Price ID to purchase
            success_url: URL to redirect on successful payment
            cancel_url: URL to redirect if user cancels
            quantity: Quantity to purchase (default: 1)

        Returns:
            ProductCheckoutSession with checkout_url

        Example:
            session = await client.create_product_checkout(
                customer_external_id="store_123",
                price_id="price_xxx",
                quantity=1,
                success_url="https://app.com/billing?product=success",
                cancel_url="https://app.com/billing?product=canceled",
            )
            # Redirect user to: session.checkout_url
        """
        response = await self._request(
            "POST",
            "/checkout/product-sessions",
            json={
                "customer_external_id": customer_external_id,
                "price_id": price_id,
                "quantity": quantity,
                "success_url": success_url,
                "cancel_url": cancel_url,
            },
        )
        return ProductCheckoutSession(**response)

    async def get_product_prices(
        self: "GrowFlowBillingClient",
        product_id: str,
    ) -> list[Price]:
        """Get prices for a specific product.

        Args:
            product_id: Product ID or slug

        Returns:
            List of Price objects

        Raises:
            NotFoundError: If product not found
        """
        response = await self._request("GET", f"/products/{product_id}/prices")

        if isinstance(response, list):
            return [Price(**p) for p in response]
        raw = response.get("items") or response.get("data") or response.get("prices") or []
        return [Price(**p) for p in raw]

    async def get_customer_products(
        self: "GrowFlowBillingClient",
        external_id: str,
    ) -> list[dict[str, Any]]:
        """Get products purchased by a customer.

        Args:
            external_id: Customer's external ID

        Returns:
            List of dictionaries with product_id, product_name, price_id,
            quantity, and purchased_at fields
        """
        response = await self._request("GET", f"/subscribers/{external_id}/products")
        return response.get("items", [])
