# DO NOT EDIT — generated by _sdk_gen/ from the OpenAPI spec.
# Regenerate with: ./generate.sh
from __future__ import annotations

from typing import Any

from goodmem._base import AsyncCRUDNamespace, CRUDNamespace
from goodmem._base import _op_meta, _expand_label_filters
from goodmem._base import _op_meta, _prepare_create_payload
from goodmem._generated.models.api_key_response import ApiKeyResponse
from goodmem._generated.models.create_api_key_request import CreateApiKeyRequest
from goodmem._generated.models.create_api_key_response import CreateApiKeyResponse
from goodmem._generated.models.list_api_keys_response import ListApiKeysResponse
from goodmem._generated.models.update_api_key_request import UpdateApiKeyRequest
from goodmem.errors import raise_for_status


class ApikeysAPIBase(CRUDNamespace):
    """Apikeys API — auto-generated structural base.

    Auto-generated structural base. Do not edit.
    Override in goodmem/api/apikeys.py to add domain-specific logic.
    """

    _base_path = "/v1/apikeys"
    _create_model = CreateApiKeyRequest
    _update_model = UpdateApiKeyRequest
    _response_model = ApiKeyResponse
    _create_response_model = CreateApiKeyResponse
    _list_response_model = ListApiKeysResponse
    _list_items_field = "keys"
    _rest_metadata: dict = {'create': {'http_method': 'POST', 'path': '/v1/apikeys', 'response': 'CreateApiKeyResponse', 'body_model': 'CreateApiKeyRequest', 'body_expr': 'CreateApiKeyRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'list': {'http_method': 'GET', 'path': '/v1/apikeys', 'response': 'ListApiKeysResponse'}, 'update': {'http_method': 'PUT', 'path': '/v1/apikeys/{id}', 'response': 'ApiKeyResponse', 'query_params': ['id'], 'body_model': 'UpdateApiKeyRequest', 'body_expr': 'UpdateApiKeyRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'delete': {'http_method': 'DELETE', 'path': '/v1/apikeys/{id}', 'response': 'None', 'query_params': ['id']}}

    def create(self, **kwargs: Any) -> Any:
        """Create a new API key

        Creates a new API key for authenticating with the API. New keys start in ACTIVE status and can be used immediately for authentication. The response includes the one-time raw API key value which will not be retrievable later - clients must save this value as it cannot be recovered. Requires CREATE_APIKEY_OWN permission (or CREATE_APIKEY_ANY for admin users). Side effects include generating cryptographically secure key material, recording creation timestamp, and tracking creator ID. Returns INVALID_ARGUMENT if expires_at is set to a time in the past.

        Args:
            labels (object, optional): Key-value pairs of metadata associated with the API key. Used for organization and filtering.
            expires_at (integer, optional): Expiration timestamp in milliseconds since epoch. If not provided, the key does not expire.
            api_key_id (string, optional): Optional client-provided UUID for idempotent creation. If not provided, server generates a new UUID. Returns ALREADY_EXISTS if ID is already in use.

        Returns:
            CreateApiKeyResponse
        """
        op = _op_meta(self, 'create')
        json_payload, data_payload, files_payload = _prepare_create_payload(
            create_model=self._create_model, op=op, kwargs=dict(kwargs),
        )
        resp = self._http.post(
            self._base_path,
            json=json_payload,
            data=data_payload,
            files=files_payload,
            headers=self._headers,
        )
        return self._handle_response(resp, self._create_response_model or self._response_model)

    def list(self, **kwargs: Any) -> Any:
        """List API keys

        Retrieves a list of API keys belonging to the authenticated user. The list includes metadata about each key but not the actual key values or key hashes for security reasons. Requires LIST_APIKEY_OWN permission (or LIST_APIKEY_ANY for admin users to view keys from any user). This is a read-only operation with no side effects.

        Returns:
            ListApiKeysResponse
        """
        op = _op_meta(self, 'list')
        params = dict(kwargs)
        resp = self._http.get(
            self._base_path,
            params=params or None,
            headers=self._headers,
        )
        return self._handle_list_response(resp)

    def update(self, *, id: str, request: UpdateApiKeyRequest | dict) -> Any:
        """Update an API key

        Updates an existing API key with new values for status or labels. IMPORTANT: Key ID, user ownership, key material, and audit fields cannot be modified - only status (ACTIVE/INACTIVE) and labels are mutable. Requires UPDATE_APIKEY_OWN permission for keys you own (or UPDATE_APIKEY_ANY for admin users to modify any user's keys). Side effects include updating the updated_at timestamp and recording the updater's user ID. This operation is idempotent - repeated identical requests have no additional effect.

        Args:
            id (str): The unique identifier of the resource to update.
            request (UpdateApiKeyRequest | dict): The update payload. Accepts a UpdateApiKeyRequest instance or a plain dict with the same fields. Only specified fields will be modified.

        Returns:
            ApiKeyResponse
        """
        if isinstance(request, dict):
            request = UpdateApiKeyRequest.model_validate(request)
        resp = self._http.put(
            f"{self._base_path}/{id}",
            json=request.model_dump(by_alias=True, exclude_unset=True),
            headers=self._headers,
        )
        return self._handle_response(resp, self._response_model)

    def delete(self, *, id: str) -> None:
        """Delete an API key

        Permanently deletes an API key. This operation cannot be undone and immediately invalidates the key for all future authentication attempts. TIP: For reversible deactivation, use PUT /v1/apikeys/{id} with status=INACTIVE instead. Requires DELETE_APIKEY_OWN permission for keys you own (or DELETE_APIKEY_ANY for admin users to delete any user's keys). Side effects include permanently removing the key record from the database and immediate authentication invalidation.

        Args:
            id (string): The unique identifier of the API key to delete
        """
        resp = self._http.delete(f"{self._base_path}/{id}", headers=self._headers)
        raise_for_status(resp)


class AsyncApikeysAPIBase(AsyncCRUDNamespace):
    """Async Apikeys API — auto-generated structural base.

    Auto-generated structural base. Do not edit.
    Override in goodmem/api/apikeys.py to add domain-specific logic.
    """

    _base_path = "/v1/apikeys"
    _create_model = CreateApiKeyRequest
    _update_model = UpdateApiKeyRequest
    _response_model = ApiKeyResponse
    _create_response_model = CreateApiKeyResponse
    _list_response_model = ListApiKeysResponse
    _list_items_field = "keys"
    _rest_metadata: dict = {'create': {'http_method': 'POST', 'path': '/v1/apikeys', 'response': 'CreateApiKeyResponse', 'body_model': 'CreateApiKeyRequest', 'body_expr': 'CreateApiKeyRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'list': {'http_method': 'GET', 'path': '/v1/apikeys', 'response': 'ListApiKeysResponse'}, 'update': {'http_method': 'PUT', 'path': '/v1/apikeys/{id}', 'response': 'ApiKeyResponse', 'query_params': ['id'], 'body_model': 'UpdateApiKeyRequest', 'body_expr': 'UpdateApiKeyRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'delete': {'http_method': 'DELETE', 'path': '/v1/apikeys/{id}', 'response': 'None', 'query_params': ['id']}}

    async def create(self, **kwargs: Any) -> Any:
        """Create a new API key

        Creates a new API key for authenticating with the API. New keys start in ACTIVE status and can be used immediately for authentication. The response includes the one-time raw API key value which will not be retrievable later - clients must save this value as it cannot be recovered. Requires CREATE_APIKEY_OWN permission (or CREATE_APIKEY_ANY for admin users). Side effects include generating cryptographically secure key material, recording creation timestamp, and tracking creator ID. Returns INVALID_ARGUMENT if expires_at is set to a time in the past.

        Args:
            labels (object, optional): Key-value pairs of metadata associated with the API key. Used for organization and filtering.
            expires_at (integer, optional): Expiration timestamp in milliseconds since epoch. If not provided, the key does not expire.
            api_key_id (string, optional): Optional client-provided UUID for idempotent creation. If not provided, server generates a new UUID. Returns ALREADY_EXISTS if ID is already in use.

        Returns:
            CreateApiKeyResponse
        """
        op = _op_meta(self, 'create')
        json_payload, data_payload, files_payload = _prepare_create_payload(
            create_model=self._create_model, op=op, kwargs=dict(kwargs),
        )
        resp = await self._http.post(
            self._base_path,
            json=json_payload,
            data=data_payload,
            files=files_payload,
            headers=self._headers,
        )
        return self._handle_response(resp, self._create_response_model or self._response_model)

    async def list(self, **kwargs: Any) -> Any:
        """List API keys

        Retrieves a list of API keys belonging to the authenticated user. The list includes metadata about each key but not the actual key values or key hashes for security reasons. Requires LIST_APIKEY_OWN permission (or LIST_APIKEY_ANY for admin users to view keys from any user). This is a read-only operation with no side effects.

        Returns:
            ListApiKeysResponse
        """
        op = _op_meta(self, 'list')
        params = dict(kwargs)
        resp = await self._http.get(
            self._base_path,
            params=params or None,
            headers=self._headers,
        )
        return self._handle_list_response(resp)

    async def update(self, *, id: str, request: UpdateApiKeyRequest | dict) -> Any:
        """Update an API key

        Updates an existing API key with new values for status or labels. IMPORTANT: Key ID, user ownership, key material, and audit fields cannot be modified - only status (ACTIVE/INACTIVE) and labels are mutable. Requires UPDATE_APIKEY_OWN permission for keys you own (or UPDATE_APIKEY_ANY for admin users to modify any user's keys). Side effects include updating the updated_at timestamp and recording the updater's user ID. This operation is idempotent - repeated identical requests have no additional effect.

        Args:
            id (str): The unique identifier of the resource to update.
            request (UpdateApiKeyRequest | dict): The update payload. Accepts a UpdateApiKeyRequest instance or a plain dict with the same fields. Only specified fields will be modified.

        Returns:
            ApiKeyResponse
        """
        if isinstance(request, dict):
            request = UpdateApiKeyRequest.model_validate(request)
        resp = await self._http.put(
            f"{self._base_path}/{id}",
            json=request.model_dump(by_alias=True, exclude_unset=True),
            headers=self._headers,
        )
        return self._handle_response(resp, self._response_model)

    async def delete(self, *, id: str) -> None:
        """Delete an API key

        Permanently deletes an API key. This operation cannot be undone and immediately invalidates the key for all future authentication attempts. TIP: For reversible deactivation, use PUT /v1/apikeys/{id} with status=INACTIVE instead. Requires DELETE_APIKEY_OWN permission for keys you own (or DELETE_APIKEY_ANY for admin users to delete any user's keys). Side effects include permanently removing the key record from the database and immediate authentication invalidation.

        Args:
            id (string): The unique identifier of the API key to delete
        """
        resp = await self._http.delete(f"{self._base_path}/{id}", headers=self._headers)
        raise_for_status(resp)

