<?php

/**
 * ============================================================
 *
 * @project   biiproject
 *
 * @author    Andika Debi Putra
 *
 * @email     andikadebiputra@gmail.com
 *
 * @website   https://biiproject.com
 *
 * @copyright Copyright (c) 2026 Andika Debi Putra
 * @license   Proprietary - All Rights Reserved
 *
 * @version   1.0.0
 *
 * @created   2026-05-01
 * ============================================================
 *
 * Unauthorized copying, modification, distribution, or use
 * of this file is strictly prohibited without prior written
 * permission from the author.
 * ============================================================
 */

namespace App\Console\Commands;

use App\Services\Monitoring\SystemMonitoringService;
use App\Services\Notification\TelegramService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class SystemHealthCheck extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'system:health-check {--force : Force send notification even if within cool-down period}';

    /**
     * The description of the console command.
     *
     * @var string
     */
    protected $description = 'Monitor system health (CPU, RAM, Disk, DB) and send alerts to Telegram if thresholds are exceeded.';

    /**
     * Thresholds for alerts.
     */
    protected $thresholds = [
        'cpu' => 80, // percentage
        'ram' => 90, // percentage
        'disk' => 90, // percentage
    ];

    /**
     * Cool-down period in minutes to prevent spamming notifications.
     */
    protected $cooldownMinutes = 30;

    /**
     * Execute the console command.
     */
    public function handle(SystemMonitoringService $monitor, TelegramService $telegram)
    {
        $this->info('Starting System Health Check...');

        $issues = [];
        $metrics = [];

        // 1. Check Database Connectivity
        try {
            DB::connection()->getPdo();
            $metrics[] = '✅ Database: Connected';
        } catch (\Exception $e) {
            $issues[] = '❌ <b>DATABASE DOWN:</b> Unable to connect to the database. Error: '.$e->getMessage();
        }

        // 2. Check CPU Usage
        $cpu = $monitor->getCpuUsage();
        $metrics[] = "📊 CPU Usage: {$cpu}%";
        if ($cpu >= $this->thresholds['cpu']) {
            $issues[] = "⚠️ <b>High CPU Usage:</b> {$cpu}% (Threshold: {$this->thresholds['cpu']}%)";
        }

        // 3. Check RAM Usage
        $ram = $monitor->getRamUsage();
        $metrics[] = "📊 RAM Usage: {$ram}%";
        if ($ram >= $this->thresholds['ram']) {
            $issues[] = "⚠️ <b>High RAM Usage:</b> {$ram}% (Threshold: {$this->thresholds['ram']}%)";
        }

        // 4. Check Disk Usage
        $disk = $monitor->getDiskUsage();
        $metrics[] = "📊 Disk Usage: {$disk}%";
        if ($disk >= $this->thresholds['disk']) {
            $issues[] = "⚠️ <b>High Disk Usage:</b> {$disk}% (Threshold: {$this->thresholds['disk']}%)";
        }

        // Output to console
        foreach ($metrics as $metric) {
            $this->line($metric);
        }

        if (empty($issues)) {
            $this->info('System health is optimal. No issues detected.');

            return 0;
        }

        $this->error(count($issues).' issue(s) detected!');

        // Check for cool-down
        $cacheKey = 'system_health_alert_last_sent';
        if (Cache::has($cacheKey) && ! $this->option('force')) {
            $this->warn('Issues detected, but notification is in cool-down period. Use --force to override.');

            return 0;
        }

        // Prepare Telegram Message
        $hostname = gethostname();
        $ip = request()->server('SERVER_ADDR') ?? gethostbyname($hostname);
        $time = now()->format('Y-m-d H:i:s');

        $message = "🚨 <b>SYSTEM HEALTH ALERT</b> 🚨\n";
        $message .= "--------------------------------\n";
        $message .= "<b>Host:</b> {$hostname} ({$ip})\n";
        $message .= "<b>Time:</b> {$time}\n";
        $message .= "--------------------------------\n\n";
        $message .= implode("\n", $issues)."\n\n";
        $message .= '<i>Please check the system dashboard for more details.</i>';

        // Send Notification
        if ($telegram->sendMessage($message)) {
            $this->info('Alert notification sent to Telegram.');
            Cache::put($cacheKey, true, now()->addMinutes($this->cooldownMinutes));
        } else {
            $this->error('Failed to send Telegram notification. Check laravel.log for details.');
        }

        return 0;
    }
}
