<?php

declare(strict_types=1);

namespace App\Framework\Deployment\Ssl\Commands;

use App\Framework\Config\Environment;
use App\Framework\Console\Attributes\ConsoleCommand;
use App\Framework\Console\ConsoleOutput;
use App\Framework\Console\ExitCode;
use App\Framework\Deployment\Ssl\Services\SslCertificateService;
use App\Framework\Deployment\Ssl\ValueObjects\SslConfiguration;

/**
 * Console command to check SSL certificate status
 */
#[ConsoleCommand(
    name: 'ssl:status',
    description: 'Check SSL certificate status and expiry'
)]
final readonly class SslStatusCommand
{
    public function __construct(
        private SslCertificateService $sslService,
        private Environment $environment,
        private ConsoleOutput $output
    ) {}

    public function execute(): ExitCode
    {
        $this->output->writeLine('📋 SSL Certificate Status');
        $this->output->writeLine('');

        try {
            // Load configuration from environment
            $config = SslConfiguration::fromEnvironment($this->environment);

            $this->output->writeLine('Domain: ' . $config->domain->value);
            $this->output->writeLine('');

            // Get certificate status
            $status = $this->sslService->getStatus(
                $config->domain,
                $config->certbotConfDir->toString()
            );

            if (!$status->exists) {
                $this->output->writeLine('❌ No certificate found for this domain');
                $this->output->writeLine('');
                $this->output->writeLine('Run "ssl:init" to obtain a certificate.');
                return ExitCode::FAILURE;
            }

            // Display certificate information
            $this->displayCertificateInfo($status);

            // Display health status with appropriate emoji
            $healthEmoji = match ($status->getHealthStatus()) {
                'healthy' => '✅',
                'expiring' => '⚠️ ',
                'expired' => '❌',
                'invalid' => '❌',
                'missing' => '❌',
                default => 'ℹ️ '
            };

            $this->output->writeLine('');
            $this->output->writeLine($healthEmoji . ' Health Status: ' . strtoupper($status->getHealthStatus()));

            // Display warnings or recommendations
            if ($status->isExpired) {
                $this->output->writeLine('');
                $this->output->writeLine('⚠️  Certificate has expired!');
                $this->output->writeLine('   Run "ssl:renew" immediately to renew the certificate.');
            } elseif ($status->isExpiring) {
                $this->output->writeLine('');
                $this->output->writeLine('⚠️  Certificate is expiring soon (< 30 days)');
                $this->output->writeLine('   Run "ssl:renew" to renew the certificate.');
            } elseif (!$status->isValid) {
                $this->output->writeLine('');
                $this->output->writeLine('⚠️  Certificate is invalid');
                if (!empty($status->errors)) {
                    $this->output->writeLine('   Errors:');
                    foreach ($status->errors as $error) {
                        $this->output->writeLine('     - ' . $error);
                    }
                }
            } else {
                $this->output->writeLine('');
                $this->output->writeLine('✅ Certificate is valid and healthy');
            }

            $this->output->writeLine('');

            return $status->isValid ? ExitCode::SUCCESS : ExitCode::FAILURE;

        } catch (\Exception $e) {
            $this->output->writeLine('');
            $this->output->writeLine('❌ Error: ' . $e->getMessage());
            $this->output->writeLine('');
            return ExitCode::FAILURE;
        }
    }

    private function displayCertificateInfo($status): void
    {
        $this->output->writeLine('Certificate Information:');
        $this->output->writeLine('─────────────────────────────────────────');

        if ($status->subject) {
            $this->output->writeLine('Subject:          ' . $status->subject);
        }

        if ($status->issuer) {
            $this->output->writeLine('Issuer:           ' . $status->issuer);
        }

        if ($status->notBefore) {
            $this->output->writeLine('Valid From:       ' . $status->notBefore->format('Y-m-d H:i:s T'));
        }

        if ($status->notAfter) {
            $this->output->writeLine('Valid Until:      ' . $status->notAfter->format('Y-m-d H:i:s T'));
        }

        if ($status->daysUntilExpiry !== null) {
            $expiryColor = $status->isExpiring ? '⚠️  ' : '';
            $this->output->writeLine('Days Until Expiry: ' . $expiryColor . $status->daysUntilExpiry . ' days');
        }

        $this->output->writeLine('─────────────────────────────────────────');
    }
}
