<?php

namespace App\Console\Commands;

use App\Services\MonitoringService;
use Illuminate\Console\Command;

class MonitorSystemHealth extends Command
{
    protected $signature = 'monitor:health';
    protected $description = 'Monitor system health and performance metrics';

    public function handle(MonitoringService $monitoringService): int
    {
        $this->info('Checking system health...');

        // Check database
        $dbHealth = $monitoringService->checkDatabase();
        $this->line("Database: {$dbHealth['status']}");
        if (isset($dbHealth['response_time_ms'])) {
            $this->line("  Response time: {$dbHealth['response_time_ms']}ms");
        }

        // Check cache
        $cacheHealth = $monitoringService->checkCache();
        $this->line("Cache: {$cacheHealth['status']}");
        if (isset($cacheHealth['response_time_ms'])) {
            $this->line("  Response time: {$cacheHealth['response_time_ms']}ms");
        }

        // Get system metrics
        $metrics = $monitoringService->getSystemMetrics();
        $this->newLine();
        $this->info('System Metrics:');
        $this->line("Memory Usage: {$metrics['memory_usage']['used_mb']}MB / {$metrics['memory_usage']['limit']}");
        $this->line("Disk Usage: {$metrics['disk_usage']['usage_percent']}% ({$metrics['disk_usage']['used_gb']}GB / {$metrics['disk_usage']['total_gb']}GB)");
        if ($metrics['database_size']) {
            $this->line("Database Size: {$metrics['database_size']}MB");
        }
        $this->line("Active Users (24h): {$metrics['active_users']}");
        $this->line("Pending Orders: {$metrics['pending_orders']}");

        // Log metrics
        $monitoringService->logPerformanceMetrics();

        return Command::SUCCESS;
    }
}
