<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Domain\Status\Models\StatusComponent;
use App\Domain\Status\Services\StatusChecker;
use Illuminate\Console\Command;

/**
 * StatusCheckCommand
 *
 * Tüm aktif bileşenleri kontrol eder ve sonuçları kaydeder.
 * `onox:status-check` komutu her dakika çalıştırılır;
 * her bileşenin check_interval_seconds aralığına uygun olup olmadığı
 * burada değerlendirilir.
 *
 * Schedule: routes/console.php — everyMinute()->withoutOverlapping()
 */
class StatusCheckCommand extends Command
{
    protected $signature = 'onox:status-check {--component= : Sadece belirli bir bileşeni kontrol et (slug)}';

    protected $description = 'Check all enabled status components and persist results';

    public function handle(StatusChecker $checker): int
    {
        $query = StatusComponent::where('check_type', '!=', 'manual');

        if ($slug = $this->option('component')) {
            $query->where('slug', $slug);
        }

        $components = $query->get();

        if ($components->isEmpty()) {
            $this->warn('No components to check.');

            return 0;
        }

        $checked = 0;
        $skipped = 0;

        foreach ($components as $component) {
            // Skip if interval has not elapsed yet
            if (
                $component->last_check_at !== null
                && $component->last_check_at->gt(now()->subSeconds($component->check_interval_seconds))
            ) {
                $skipped++;

                continue;
            }

            try {
                $result = $checker->checkComponent($component);
                $icon = $result['success'] ? '✓' : '✗';
                $status = $result['error'] ?? 'OK';
                $this->line(sprintf('%s %-30s %s (%dms)', $icon, $component->name, $status, $result['duration_ms']));
            } catch (\Throwable $e) {
                $this->error("Error checking {$component->name}: {$e->getMessage()}");
            }

            $checked++;
        }

        $this->line("Done. Checked: {$checked}, Skipped (interval): {$skipped}");

        return 0;
    }
}
