import secrets
from dataclasses import dataclass, field


@dataclass(frozen=True)
class CertificateMetadata:
    """
    Represents metadata for a certificate, including its common name and a secure password.

    Attributes:
        common_name (str): The common name assigned to the certificate.
        password (str): An autogenerated, secure, password for the certificate. This is hidden from the representation.
    """

    common_name: str = field(
        metadata={"description": "The common name assigned to the certificate."}
    )
    password: str = field(
        init=False,
        repr=False,
        default_factory=lambda: secrets.token_urlsafe(32),
        metadata={
            "description": "Autogenerated, secure, password for the certificate."
        },
    )

    def __post_init__(self):
        """
        Validates the common name and password after initialization.

        Raises:
            ValueError: If the common name or password fails validation rules
        """
        # Validate common name
        if not self.common_name.strip():
            raise ValueError("Common name cannot be empty.")

        if len(self.common_name) > 64:
            raise ValueError(f"Common name must not exceed 64 characters, but got {len(self.common_name)} characters.")

        # Validate password
        if len(self.password) < 16:
            raise ValueError(
                f"Password must be at least 16 characters long, " f"but got {len(self.password)} characters."
            )
