<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\Install\EnvChecker;
use App\Services\Install\LockGuard;
use Illuminate\Console\Command;

/**
 *   php artisan wdot:status
 *
 * 설치 상태 + 환경 점검을 한 번에 진단.
 */
final class WdotStatusCommand extends Command
{
    protected $signature = 'wdot:status {--json : JSON 출력}';

    protected $description = 'W·Dot CMS 설치 / 환경 상태 진단';

    public function handle(LockGuard $lock, EnvChecker $env): int
    {
        $installed = $lock->verify();
        $lockData = null;
        if (is_file($lock->path())) {
            $lockData = json_decode((string) file_get_contents($lock->path()), true);
        }

        $report = $env->run();

        if ($this->option('json')) {
            $this->line(json_encode([
                'installed' => $installed,
                'lock'      => $lockData,
                'env_passed' => $report['passed'],
                'env_checks' => $report['checks'],
            ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) ?: '');

            return self::SUCCESS;
        }

        $this->line('');
        $this->line('  <bg=cyan;fg=white> W·Dot CMS Status </>');
        $this->line('  installed       : '.($installed ? '<fg=green>YES</>' : '<fg=red>NO</>'));
        if ($lockData) {
            $this->line('  installed_at    : '.($lockData['installed_at'] ?? '—'));
            $this->line('  installer_ip    : '.($lockData['installer_ip'] ?? '—'));
            $this->line('  installer_ver   : '.($lockData['installer_version'] ?? '—'));
            $this->line('  super_admin_id  : '.($lockData['super_admin_id'] ?? '—'));
            $this->line('  hmac_valid      : '.($installed ? '<fg=green>YES</>' : '<fg=red>NO</>'));
        }

        $this->newLine();
        $this->line('  환경 점검: '.($report['passed'] ? '<fg=green>PASS</>' : '<fg=red>FAIL</>'));
        foreach ($report['checks'] as $c) {
            if ($c['status'] === 'pass') {
                continue;
            }
            $this->line(sprintf('    %s %-32s %s',
                $c['status'] === 'warn' ? '<fg=yellow>⚠</>' : '<fg=red>✗</>',
                $c['label'],
                $c['detail'],
            ));
        }

        return self::SUCCESS;
    }
}
