<?php

namespace App\Console\Commands;

use App\Services\System\SystemHealthService;
use Illuminate\Console\Command;

class RemoteMatchHealthCommand extends Command
{
    protected $signature = 'remotematch:health {--fail-on-warning : Return a non-zero exit code when warnings exist}';

    protected $description = 'Run RemoteMatch marketplace installation and production readiness checks.';

    public function handle(SystemHealthService $health): int
    {
        $checks = $health->checks();
        $summary = $health->summary();

        $this->table(
            ['Status', 'Group', 'Check', 'Details', 'Action'],
            collect($checks)->map(fn (array $check): array => [
                strtoupper($check['status']),
                $check['group'],
                $check['title'],
                $check['details'],
                $check['action'] ?: '-',
            ])->all()
        );

        $this->line("Passed: {$summary['pass']} | Warnings: {$summary['warning']} | Failed: {$summary['fail']} | Total: {$summary['total']}");

        if ($summary['fail'] > 0 || ($this->option('fail-on-warning') && $summary['warning'] > 0)) {
            return self::FAILURE;
        }

        return self::SUCCESS;
    }
}
