from __future__ import annotations

import httpx

from .models import *


class KeysKeysAPI:
    """API endpoints for Keys."""

    def __init__(self, client: httpx.AsyncClient):
        """Initialize sub-client with shared httpx client."""
        self._client = client

    async def list(self, page: int | None = None, page_size: int | None = None) -> list[PaginatedAPIKeyListList]:
        """
        ViewSet for API key management. Endpoints: - GET /api/keys/ - List
        user's API keys - POST /api/keys/ - Create a new API key - GET
        /api/keys/{id}/ - Get API key details - DELETE /api/keys/{id}/ -
        Deactivate API key - POST /api/keys/{id}/rotate/ - Rotate API key - POST
        /api/keys/{id}/reactivate/ - Reactivate API key
        """
        url = "/api/keys/"
        response = await self._client.get(url, params={"page": page if page is not None else None, "page_size": page_size if page_size is not None else None})
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return PaginatedAPIKeyListList.model_validate(response.json())


    async def create(self, data: APIKeyCreateRequest) -> APIKeyCreate:
        """
        Create a new API key.
        """
        url = "/api/keys/"
        response = await self._client.post(url, json=data.model_dump(exclude_unset=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return APIKeyCreate.model_validate(response.json())


    async def retrieve(self, id: str) -> APIKeyDetail:
        """
        ViewSet for API key management. Endpoints: - GET /api/keys/ - List
        user's API keys - POST /api/keys/ - Create a new API key - GET
        /api/keys/{id}/ - Get API key details - DELETE /api/keys/{id}/ -
        Deactivate API key - POST /api/keys/{id}/rotate/ - Rotate API key - POST
        /api/keys/{id}/reactivate/ - Reactivate API key
        """
        url = f"/api/keys/{id}/"
        response = await self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return APIKeyDetail.model_validate(response.json())


    async def update(self, id: str) -> APIKeyList:
        """
        ViewSet for API key management. Endpoints: - GET /api/keys/ - List
        user's API keys - POST /api/keys/ - Create a new API key - GET
        /api/keys/{id}/ - Get API key details - DELETE /api/keys/{id}/ -
        Deactivate API key - POST /api/keys/{id}/rotate/ - Rotate API key - POST
        /api/keys/{id}/reactivate/ - Reactivate API key
        """
        url = f"/api/keys/{id}/"
        response = await self._client.put(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return APIKeyList.model_validate(response.json())


    async def partial_update(self, id: str) -> APIKeyList:
        """
        ViewSet for API key management. Endpoints: - GET /api/keys/ - List
        user's API keys - POST /api/keys/ - Create a new API key - GET
        /api/keys/{id}/ - Get API key details - DELETE /api/keys/{id}/ -
        Deactivate API key - POST /api/keys/{id}/rotate/ - Rotate API key - POST
        /api/keys/{id}/reactivate/ - Reactivate API key
        """
        url = f"/api/keys/{id}/"
        response = await self._client.patch(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return APIKeyList.model_validate(response.json())


    async def destroy(self, id: str) -> None:
        """
        Deactivate an API key (soft delete).
        """
        url = f"/api/keys/{id}/"
        response = await self._client.delete(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return None


    async def reactivate_create(self, id: str) -> APIKeyList:
        """
        Reactivate a deactivated API key.
        """
        url = f"/api/keys/{id}/reactivate/"
        response = await self._client.post(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return APIKeyList.model_validate(response.json())


    async def rotate_create(self, id: str) -> APIKeyList:
        """
        Rotate an API key (generate new key).
        """
        url = f"/api/keys/{id}/rotate/"
        response = await self._client.post(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return APIKeyList.model_validate(response.json())


