"""Admin API endpoints for superadmin dashboard."""

from __future__ import annotations

from typing import TYPE_CHECKING
from uuid import UUID

from vikdata.models.common import PaginatedResponse
from vikdata.models.admin import (
    AdminStats,
    AdminSubscription,
    AdminPlan,
    CreatePlanRequest,
    UpdatePlanRequest,
)

if TYPE_CHECKING:
    from vikdata.client import VikdataClient


class AdminSubscriptionsAPI:
    """Admin subscription management (cross-tenant view)."""

    def __init__(self, client: "VikdataClient") -> None:
        self._client = client

    async def list(
        self,
        *,
        page: int | None = None,
        per_page: int | None = None,
        status: str | None = None,
    ) -> PaginatedResponse[AdminSubscription]:
        """List all subscriptions across tenants.

        Requires superadmin role.

        Args:
            page: Page number (default: 1)
            per_page: Items per page (default: 20, max: 100)
            status: Filter by status (from lookup)

        Returns:
            Paginated list of subscriptions
        """
        params = {
            "page": page,
            "per_page": per_page,
            "status": status,
        }
        params = {k: v for k, v in params.items() if v is not None}

        return await self._client.request(
            "GET",
            "/api/v1/admin/subscriptions",
            params=params,
            response_model=PaginatedResponse[AdminSubscription],
        )


class AdminPlansAPI:
    """Admin plan management."""

    def __init__(self, client: "VikdataClient") -> None:
        self._client = client

    async def list(
        self,
        *,
        include_private: bool | None = None,
    ) -> list[AdminPlan]:
        """List all plans (including private plans).

        Requires superadmin role.

        Args:
            include_private: Include private plans

        Returns:
            List of plans
        """
        params = {}
        if include_private is not None:
            params["include_private"] = include_private

        response = await self._client.request(
            "GET",
            "/api/v1/admin/plans",
            params=params if params else None,
        )
        if isinstance(response, dict) and "data" in response:
            return [AdminPlan.model_validate(p) for p in response["data"]]
        return [AdminPlan.model_validate(p) for p in response]

    async def get(self, plan_id: UUID) -> AdminPlan:
        """Get a plan by ID.

        Requires superadmin role.

        Args:
            plan_id: Plan ID

        Returns:
            Plan details
        """
        return await self._client.request(
            "GET",
            f"/api/v1/admin/plans/{plan_id}",
            response_model=AdminPlan,
        )

    async def create(self, data: CreatePlanRequest) -> AdminPlan:
        """Create a new plan.

        Requires superadmin role.

        Args:
            data: Plan creation data

        Returns:
            Created plan
        """
        return await self._client.request(
            "POST",
            "/api/v1/admin/plans",
            json=data,
            response_model=AdminPlan,
        )

    async def update(
        self,
        plan_id: UUID,
        data: UpdatePlanRequest,
    ) -> AdminPlan:
        """Update a plan.

        Requires superadmin role.

        Args:
            plan_id: Plan ID
            data: Plan update data

        Returns:
            Updated plan
        """
        return await self._client.request(
            "PATCH",
            f"/api/v1/admin/plans/{plan_id}",
            json=data,
            response_model=AdminPlan,
        )

    async def delete(self, plan_id: UUID) -> None:
        """Delete a plan.

        Plans with active subscriptions cannot be deleted.
        Requires superadmin role.

        Args:
            plan_id: Plan ID
        """
        await self._client.request(
            "DELETE",
            f"/api/v1/admin/plans/{plan_id}",
        )


class AdminAPI:
    """Admin API endpoints for superadmin dashboard.

    Requires superadmin role for all operations.
    """

    def __init__(self, client: "VikdataClient") -> None:
        self._client = client
        self.subscriptions = AdminSubscriptionsAPI(client)
        self.plans = AdminPlansAPI(client)

    async def stats(self) -> AdminStats:
        """Get admin dashboard statistics.

        Requires superadmin role.

        Returns:
            Dashboard statistics
        """
        return await self._client.request(
            "GET",
            "/api/v1/admin/stats",
            response_model=AdminStats,
        )
