"""Tenants API endpoints for multi-tenant management."""

from __future__ import annotations

from typing import Any, TYPE_CHECKING
from uuid import UUID

from vikdata.models.tenant import (
    TenantCreate,
    TenantListResponse,
    TenantResponse,
    TenantSettingsUpdate,
    TenantStatusResponse,
    TenantUpdate,
)

if TYPE_CHECKING:
    from vikdata.client import VikdataClient


class TenantsAPI:
    """Tenants API endpoints.

    Handles admin-level tenant operations.
    Regular users cannot access these endpoints.
    """

    def __init__(self, client: "VikdataClient") -> None:
        """Initialize tenants API.

        Args:
            client: VikdataClient instance
        """
        self._client = client

    async def list(
        self,
        page: int = 1,
        per_page: int = 20,
        status: str | None = None,
        search: str | None = None,
    ) -> TenantListResponse:
        """List all tenants (admin only).

        Args:
            page: Page number (default: 1)
            per_page: Items per page (default: 20, max: 100)
            status: Filter by status (e.g., 'active', 'suspended')
            search: Search in name and slug

        Returns:
            TenantListResponse with paginated list of tenants

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing 'tenants:read' permission
        """
        params: dict[str, Any] = {
            "page": page,
            "per_page": per_page,
        }
        if status:
            params["status"] = status
        if search:
            params["search"] = search

        return await self._client.request(
            "GET",
            "/api/v1/tenants",
            params=params,
            response_model=TenantListResponse,
        )

    async def create(
        self,
        name: str,
        slug: str,
        settings: dict[str, Any] | None = None,
    ) -> TenantResponse:
        """Create a new tenant (admin only).

        Args:
            name: Tenant display name
            slug: Tenant slug (used in URLs/subdomains)
            settings: Optional tenant-specific configuration settings

        Returns:
            TenantResponse with created tenant

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing 'tenants:write' permission
            ValidationError: Invalid input data
        """
        request = TenantCreate(name=name, slug=slug, settings=settings)
        return await self._client.request(
            "POST",
            "/api/v1/tenants",
            json=request,
            response_model=TenantResponse,
        )

    async def get(self, tenant_id: UUID) -> TenantResponse:
        """Get a specific tenant by ID (admin only).

        Args:
            tenant_id: Tenant ID

        Returns:
            TenantResponse with tenant details

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing 'tenants:read' permission
            ResourceNotFoundError: Tenant not found
        """
        return await self._client.request(
            "GET",
            f"/api/v1/tenants/{tenant_id}",
            response_model=TenantResponse,
        )

    async def update(
        self,
        tenant_id: UUID,
        name: str | None = None,
        settings: dict[str, Any] | None = None,
    ) -> TenantResponse:
        """Update a tenant (admin only).

        Args:
            tenant_id: Tenant ID
            name: Optional new tenant name
            settings: Optional new settings (replaces existing)

        Returns:
            TenantResponse with updated tenant

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing 'tenants:write' permission
            ResourceNotFoundError: Tenant not found
        """
        request = TenantUpdate(name=name, settings=settings)
        return await self._client.request(
            "PATCH",
            f"/api/v1/tenants/{tenant_id}",
            json=request,
            response_model=TenantResponse,
        )

    async def suspend(self, tenant_id: UUID) -> TenantStatusResponse:
        """Suspend a tenant (admin only).

        Suspended tenants cannot access the system until reactivated.

        Args:
            tenant_id: Tenant ID

        Returns:
            TenantStatusResponse with new status

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing 'tenants:write' permission
            ResourceNotFoundError: Tenant not found
            ValidationError: Tenant already suspended
        """
        return await self._client.request(
            "POST",
            f"/api/v1/tenants/{tenant_id}/suspend",
            response_model=TenantStatusResponse,
        )

    async def activate(self, tenant_id: UUID) -> TenantStatusResponse:
        """Activate a suspended tenant (admin only).

        Args:
            tenant_id: Tenant ID

        Returns:
            TenantStatusResponse with new status

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing 'tenants:write' permission
            ResourceNotFoundError: Tenant not found
            ValidationError: Tenant already active
        """
        return await self._client.request(
            "POST",
            f"/api/v1/tenants/{tenant_id}/activate",
            response_model=TenantStatusResponse,
        )

    async def delete(self, tenant_id: UUID) -> None:
        """Delete a tenant (admin only).

        This is a soft delete - the tenant is marked as deleted but not removed from the database.

        Args:
            tenant_id: Tenant ID

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing 'tenants:delete' permission
            ResourceNotFoundError: Tenant not found
        """
        await self._client.request(
            "DELETE",
            f"/api/v1/tenants/{tenant_id}",
        )
