# This file is auto-generated by oagen. Do not edit.

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from typing import cast
from typing import Any, Dict, List, Literal, Optional, Union
from workos._types import _raise_deserialize_error
from workos._types import _format_datetime, _parse_datetime

from .api_key_updated_data_owner import ApiKeyUpdatedDataOwner
from .api_key_updated_data_previous_attribute import ApiKeyUpdatedDataPreviousAttribute
from .user_api_key_updated_data_owner import UserApiKeyUpdatedDataOwner


@dataclass(slots=True)
class ApiKeyUpdatedData:
    """The event payload."""

    object: Literal["api_key"]
    """Distinguishes the API key object."""
    id: str
    """Unique identifier of the API key."""
    owner: Union["ApiKeyUpdatedDataOwner", "UserApiKeyUpdatedDataOwner"]
    """The owner of the API key."""
    name: str
    """The name of the API key."""
    obfuscated_value: str
    """The obfuscated value of the API key."""
    last_used_at: Optional[str]
    """The timestamp when the API key was last used."""
    expires_at: Optional[datetime]
    """Timestamp when the API Key expires. Null means the key does not expire."""
    permissions: List[str]
    """The permissions granted to the API key."""
    created_at: str
    """The timestamp when the API key was created."""
    updated_at: str
    """The timestamp when the API key was last updated."""
    previous_attributes: "ApiKeyUpdatedDataPreviousAttribute"
    """Previous API key attributes before the update."""

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ApiKeyUpdatedData":
        """Deserialize from a dictionary."""
        try:
            _owner_raw = data["owner"]
            _owner_data = cast(Dict[str, Any], _owner_raw)
            _owner_disc = cast(str, _owner_data.get("type"))
            _owner_disc_map: Dict[str, Any] = {
                "organization": ApiKeyUpdatedDataOwner,
                "user": UserApiKeyUpdatedDataOwner,
            }
            _owner_cls = _owner_disc_map.get(_owner_disc)
            if _owner_cls is None:
                raise ValueError(
                    f"Unknown discriminator 'type' for ApiKeyUpdatedData.owner: {_owner_disc!r}. "
                    f"Expected one of {sorted(_owner_disc_map)}."
                )
            return cls(
                object=data.get("object", "api_key"),
                id=data["id"],
                owner=_owner_cls.from_dict(_owner_data),
                name=data["name"],
                obfuscated_value=data["obfuscated_value"],
                last_used_at=data["last_used_at"],
                expires_at=_parse_datetime(_v_expires_at)
                if (_v_expires_at := data["expires_at"]) is not None
                else None,
                permissions=data["permissions"],
                created_at=data["created_at"],
                updated_at=data["updated_at"],
                previous_attributes=ApiKeyUpdatedDataPreviousAttribute.from_dict(
                    cast(Dict[str, Any], data["previous_attributes"])
                ),
            )
        except (KeyError, ValueError) as e:
            _raise_deserialize_error("ApiKeyUpdatedData", e)

    def to_dict(self) -> Dict[str, Any]:
        """Serialize to a dictionary."""
        result: Dict[str, Any] = {}
        result["object"] = self.object
        result["id"] = self.id
        result["owner"] = self.owner.to_dict()
        result["name"] = self.name
        result["obfuscated_value"] = self.obfuscated_value
        if self.last_used_at is not None:
            result["last_used_at"] = self.last_used_at
        else:
            result["last_used_at"] = None
        if self.expires_at is not None:
            result["expires_at"] = _format_datetime(self.expires_at)
        else:
            result["expires_at"] = None
        result["permissions"] = self.permissions
        result["created_at"] = self.created_at
        result["updated_at"] = self.updated_at
        result["previous_attributes"] = self.previous_attributes.to_dict()
        return result
