"""Authentication resource for the Contiss API."""

from typing import Optional

from ..types import APIKey, APIKeyCreate, APIKeyList, AuthResponse
from .base import BaseResource


class AuthResource(BaseResource):
    """Handles authentication-related operations."""

    def create_api_key(
        self, name: str, expires_in_days: Optional[int] = None
    ) -> APIKeyCreate:
        """Create a new API key.

        Requires JWT token authentication.

        Args:
            name: Name/description for the API key
            expires_in_days: Optional number of days until expiration (max 365)

        Returns:
            APIKeyCreate object with the new key (key only shown once)

        Raises:
            AuthenticationError: If not authenticated with JWT
            ValidationError: If parameters are invalid
        """
        payload = {"name": name}
        if expires_in_days is not None:
            payload["expires_in_days"] = expires_in_days

        response = self._client.post("/auth/api-keys", json=payload)
        return APIKeyCreate(**response)

    def list_api_keys(self) -> APIKeyList:
        """List all API keys for the current user.

        Requires JWT token authentication.

        Returns:
            APIKeyList with all keys (actual key values not included)

        Raises:
            AuthenticationError: If not authenticated with JWT
        """
        response = self._client.get("/auth/api-keys")
        return APIKeyList(**response)

    def delete_api_key(self, key_id: str) -> bool:
        """Delete an API key.

        Requires JWT token authentication.

        Args:
            key_id: UUID of the API key to delete

        Returns:
            True if deletion was successful

        Raises:
            AuthenticationError: If not authenticated with JWT
            NotFoundError: If key doesn't exist or doesn't belong to user
        """
        response = self._client.delete(f"/auth/api-keys/{key_id}")
        return response.get("success", False)
