<?php

declare(strict_types=1);

namespace App\Framework\Process\ValueObjects\Ssl;

/**
 * SSL Certificate Information.
 */
final readonly class CertificateInfo
{
    public function __construct(
        public string $subject,
        public string $issuer,
        public \DateTimeImmutable $validFrom,
        public \DateTimeImmutable $validTo,
        public array $subjectAltNames,
        public bool $isSelfSigned,
        public ?string $serialNumber = null,
        public ?string $signatureAlgorithm = null
    ) {
    }

    /**
     * Prüft, ob das Zertifikat gültig ist.
     */
    public function isValid(): bool
    {
        $now = new \DateTimeImmutable();

        return $now >= $this->validFrom && $now <= $this->validTo;
    }

    /**
     * Prüft, ob das Zertifikat bald abläuft.
     */
    public function isExpiringSoon(int $daysThreshold = 30): bool
    {
        $now = new \DateTimeImmutable();
        $threshold = $now->modify("+{$daysThreshold} days");

        return $this->validTo <= $threshold;
    }

    /**
     * Gibt die verbleibenden Tage bis zum Ablauf zurück.
     */
    public function getDaysUntilExpiry(): int
    {
        $now = new \DateTimeImmutable();
        $diff = $now->diff($this->validTo);

        return $diff->days * ($diff->invert ? -1 : 1);
    }

    /**
     * Prüft, ob das Zertifikat abgelaufen ist.
     */
    public function isExpired(): bool
    {
        return new \DateTimeImmutable() > $this->validTo;
    }

    /**
     * Konvertiert zu Array.
     *
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'subject' => $this->subject,
            'issuer' => $this->issuer,
            'valid_from' => $this->validFrom->format('Y-m-d H:i:s'),
            'valid_to' => $this->validTo->format('Y-m-d H:i:s'),
            'subject_alt_names' => $this->subjectAltNames,
            'is_self_signed' => $this->isSelfSigned,
            'is_valid' => $this->isValid(),
            'is_expired' => $this->isExpired(),
            'days_until_expiry' => $this->getDaysUntilExpiry(),
            'serial_number' => $this->serialNumber,
            'signature_algorithm' => $this->signatureAlgorithm,
        ];
    }
}
