"""JWT claim models."""

from dataclasses import dataclass, field
from typing import Any


@dataclass
class TokenClaims:
    """Validated JWT claims.

    Attributes:
        sub: Subject (user ID or API key ID)
        tenant_id: Tenant identifier
        email: User email (empty string for API keys)
        name: User display name (None for API keys)
        permissions: List of permission strings resolved from roles
        roles: List of role names/slugs
        exp: Expiration timestamp (Unix)
        iat: Issued-at timestamp (Unix)
        iss: Token issuer
        aud: Token audience (single string or list)
        jti: JWT ID (for token revocation)
        entity_type: Type of authenticated entity ("user" or "api_key")
    """

    sub: str
    email: str
    permissions: list[str]
    roles: list[str]
    exp: int
    iat: int
    iss: str
    aud: str | list[str]
    tenant_id: str | None = None
    name: str | None = None
    jti: str | None = None
    entity_type: str = "user"
    is_superadmin: bool = False

    @classmethod
    def from_payload(cls, payload: dict[str, Any]) -> "TokenClaims":
        """Create from JWT payload.

        Args:
            payload: Decoded JWT payload dictionary

        Returns:
            TokenClaims instance with extracted values
        """
        return cls(
            sub=payload["sub"],
            email=payload.get("email", ""),
            name=payload.get("name"),
            permissions=payload.get("permissions", []),
            roles=payload.get("roles", []),
            exp=payload["exp"],
            iat=payload["iat"],
            iss=payload["iss"],
            aud=payload["aud"],
            tenant_id=payload.get("tenant_id"),
            jti=payload.get("jti"),
            entity_type=payload.get("entity_type", "user"),
            is_superadmin=payload.get("is_superadmin", False),
        )

    @property
    def user_id(self) -> str:
        """Alias for sub (backward compatibility)."""
        return self.sub

    @property
    def is_api_key(self) -> bool:
        """Check if this token represents an API key."""
        return self.entity_type == "api_key"

    @property
    def is_user(self) -> bool:
        """Check if this token represents a user."""
        return self.entity_type == "user"
