"""
Credentials Resource

Manage CLR (Comprehensive Learner Record) verifiable credentials.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from timeback_common import serialize_input, validate_with_schema

from ..types.inputs import ClrCredentialInput
from ..types.responses import ClrCredential

if TYPE_CHECKING:
    from ..lib.transport import Transport


class CredentialsResource:
    """
    Credentials resource for CLR credential management.

    Provides the ability to upsert verifiable CLR credentials.
    The platform acts as the publisher, digitally signing credentials
    to ensure their authenticity and integrity.
    """

    def __init__(self, transport: Transport) -> None:
        self._transport = transport

    async def upsert(
        self, credential: ClrCredential | ClrCredentialInput | dict[str, Any]
    ) -> ClrCredential:
        """
        Upsert a Comprehensive Learner Record (CLR) credential.

        Creates a new credential or updates an existing one based on the credential ID.
        The platform will digitally sign the credential, adding a cryptographic proof
        to ensure authenticity.

        Args:
            credential: The CLR credential to upsert

        Returns:
            The upserted credential with platform-added proof
        """
        validate_with_schema(ClrCredentialInput, credential, "CLR credential")
        payload = serialize_input(credential, ClrCredentialInput)
        result = await self._transport.post(
            f"{self._transport.paths.credentials}/",
            payload,
        )
        return ClrCredential.model_validate(result)
