"""Tests for the certificate validation module."""

from __future__ import annotations

import pytest
from cryptography import x509

from ecp_auth.exceptions import CertificateExpiredError, CertificateValidationError
from ecp_auth.parsers import CertificateInfo, extract_certificate_info
from ecp_auth.validators import (
    validate_certificate,
    validate_certificate_structure,
    validate_expiration,
    validate_key_usage,
)


class TestValidateCertificate:
    """Tests for the full certificate validation pipeline."""

    def test_valid_certificate(
        self, self_signed_certificate: x509.Certificate
    ) -> None:
        """Test that a valid certificate passes all checks."""
        info = validate_certificate(self_signed_certificate)

        assert isinstance(info, CertificateInfo)
        assert info.common_name == "Test User"

    def test_expired_certificate(
        self, expired_certificate: x509.Certificate
    ) -> None:
        """Test that an expired certificate raises CertificateExpiredError."""
        with pytest.raises(CertificateExpiredError):
            validate_certificate(expired_certificate)


class TestValidateExpiration:
    """Tests for certificate expiration validation."""

    def test_valid_expiration(
        self, self_signed_certificate: x509.Certificate
    ) -> None:
        """Test that a non-expired certificate passes."""
        info = extract_certificate_info(self_signed_certificate)
        validate_expiration(info)  # Should not raise

    def test_expired_certificate(
        self, expired_certificate: x509.Certificate
    ) -> None:
        """Test that an expired certificate raises."""
        info = extract_certificate_info(expired_certificate)
        with pytest.raises(CertificateExpiredError, match="expired"):
            validate_expiration(info)


class TestValidateKeyUsage:
    """Tests for key usage validation."""

    def test_valid_key_usage(
        self, self_signed_certificate: x509.Certificate
    ) -> None:
        """Test certificate with digitalSignature key usage."""
        info = extract_certificate_info(self_signed_certificate)
        validate_key_usage(info)  # Should not raise

    def test_missing_digital_signature(
        self, expired_certificate: x509.Certificate
    ) -> None:
        """Cert without KeyUsage extension should pass (absent != forbidden)."""
        info = extract_certificate_info(expired_certificate)
        validate_key_usage(info)  # Should not raise — no extension is OK


class TestValidateCertificateStructure:
    """Tests for certificate structure validation."""

    def test_valid_structure(
        self, self_signed_certificate: x509.Certificate
    ) -> None:
        """Test that a well-formed certificate passes structure checks."""
        validate_certificate_structure(self_signed_certificate)  # Should not raise
