"""Admin Products API endpoint mixin (for product management)."""

from typing import TYPE_CHECKING, Any

from growflow_billing.models.admin_product import AdminProduct

if TYPE_CHECKING:
    from growflow_billing.client import GrowFlowBillingClient


class AdminProductsMixin:
    """Mixin for admin product management API calls.

    These endpoints require admin-level API access and are used for
    managing products in the GrowFlow Billing system.
    """

    async def admin_list_products(
        self: "GrowFlowBillingClient",
        is_active: bool | None = None,
    ) -> list[AdminProduct]:
        """List all products from GrowFlow Billing.

        Args:
            is_active: Filter by active status (optional)

        Returns:
            List of AdminProduct objects

        Example:
            products = await client.admin_list_products()
            for product in products:
                print(f"{product.name}: {product.price_cents} cents")
        """
        params: dict[str, Any] = {}
        if is_active is not None:
            params["is_active"] = is_active

        response = await self._request(
            "GET",
            "/admin/products/local",
            params=params if params else None,
        )

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

    async def admin_get_product(
        self: "GrowFlowBillingClient",
        product_id: str,
    ) -> AdminProduct:
        """Get a single product by ID.

        Args:
            product_id: Product ID (UUID)

        Returns:
            AdminProduct object

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

    async def admin_create_product(
        self: "GrowFlowBillingClient",
        name: str,
        price_cents: int,
        currency: str = "eur",
        description: str | None = None,
        recurring_interval: str | None = None,
        category: str | None = None,
        feature_slug: str | None = None,
        extra_data: dict[str, Any] | None = None,
        sync_stripe: bool = False,
    ) -> AdminProduct:
        """Create a new product in GrowFlow Billing.

        Args:
            name: Product name
            price_cents: Price in cents (e.g., 1999 for €19.99)
            currency: Currency code (default: "eur")
            description: Product description
            recurring_interval: Billing interval ("month", "year", or None for one-time)
            category: Product category
            feature_slug: Feature slug for feature-based access control
            extra_data: Additional metadata
            sync_stripe: Whether to sync to Stripe immediately

        Returns:
            Created AdminProduct object

        Example:
            product = await client.admin_create_product(
                name="Premium Feature Pack",
                price_cents=4999,
                description="Unlock premium features",
                category="addon",
            )
        """
        payload: dict[str, Any] = {
            "name": name,
            "price_cents": price_cents,
            "currency": currency,
        }
        if description is not None:
            payload["description"] = description
        if recurring_interval is not None:
            payload["recurring_interval"] = recurring_interval
        if category is not None:
            payload["category"] = category
        if feature_slug is not None:
            payload["feature_slug"] = feature_slug
        if extra_data is not None:
            payload["extra_data"] = extra_data
        if sync_stripe:
            payload["sync_stripe"] = sync_stripe

        response = await self._request("POST", "/admin/products/local", json=payload)
        return AdminProduct(**response)

    async def admin_update_product(
        self: "GrowFlowBillingClient",
        product_id: str,
        name: str | None = None,
        description: str | None = None,
        price_cents: int | None = None,
        currency: str | None = None,
        recurring_interval: str | None = None,
        category: str | None = None,
        feature_slug: str | None = None,
        extra_data: dict[str, Any] | None = None,
        is_active: bool | None = None,
    ) -> AdminProduct:
        """Update a product in GrowFlow Billing.

        Args:
            product_id: Product ID (UUID)
            name: New product name
            description: New description
            price_cents: New price in cents
            currency: New currency code
            recurring_interval: New billing interval
            category: New category
            feature_slug: New feature slug
            extra_data: New metadata
            is_active: Active status

        Returns:
            Updated AdminProduct object

        Raises:
            NotFoundError: If product not found
        """
        payload: dict[str, Any] = {}
        if name is not None:
            payload["name"] = name
        if description is not None:
            payload["description"] = description
        if price_cents is not None:
            payload["price_cents"] = price_cents
        if currency is not None:
            payload["currency"] = currency
        if recurring_interval is not None:
            payload["recurring_interval"] = recurring_interval
        if category is not None:
            payload["category"] = category
        if feature_slug is not None:
            payload["feature_slug"] = feature_slug
        if extra_data is not None:
            payload["extra_data"] = extra_data
        if is_active is not None:
            payload["is_active"] = is_active

        response = await self._request(
            "PATCH",
            f"/admin/products/local/{product_id}",
            json=payload,
        )
        return AdminProduct(**response)

    async def admin_delete_product(
        self: "GrowFlowBillingClient",
        product_id: str,
    ) -> None:
        """Deactivate a product in GrowFlow Billing.

        This doesn't permanently delete the product, but marks it as inactive.

        Args:
            product_id: Product ID (UUID)

        Raises:
            NotFoundError: If product not found
        """
        await self._request("DELETE", f"/admin/products/local/{product_id}")

    async def admin_sync_product_to_stripe(
        self: "GrowFlowBillingClient",
        product_id: str,
    ) -> AdminProduct:
        """Sync a local product to Stripe.

        Creates or updates the product and price in Stripe.

        Args:
            product_id: Product ID (UUID)

        Returns:
            Updated AdminProduct object with Stripe IDs

        Raises:
            NotFoundError: If product not found
        """
        response = await self._request(
            "POST",
            f"/admin/products/local/{product_id}/sync-stripe",
        )
        return AdminProduct(**response)
