<?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
 * ============================================================
 */

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;

class SystemCheck extends Command
{
    protected $signature = 'system:check';

    protected $description = 'Perform a comprehensive system health check';

    public function handle()
    {
        $this->title('BIIProject System Health Check');

        $rows = [];

        // 1. Database
        try {
            DB::connection()->getPdo();
            $rows[] = ['Database', 'PostgreSQL', '<fg=green>CONNECTED</>'];
        } catch (\Exception $e) {
            $rows[] = ['Database', 'PostgreSQL', '<fg=red>FAILED</>'];
        }

        // 2. Redis
        try {
            Redis::ping();
            $rows[] = ['Cache', 'Redis', '<fg=green>CONNECTED</>'];
        } catch (\Exception $e) {
            $rows[] = ['Cache', 'Redis', '<fg=red>FAILED</>'];
        }

        // 3. Storage
        $storageOk = true;
        try {
            Storage::disk('local')->put('health-check.txt', 'ok');
            Storage::disk('local')->delete('health-check.txt');
        } catch (\Exception $e) {
            $storageOk = false;
        }
        $rows[] = ['Storage', 'Local Writable', $storageOk ? '<fg=green>OK</>' : '<fg=red>FAILED</>'];

        // 4. AI
        $aiEnabled = get_setting('ai_enabled', false);
        $aiProvider = get_setting('ai_provider', 'N/A');
        $rows[] = ['Intelligence', 'AI Service', $aiEnabled ? "<fg=green>ENABLED ({$aiProvider})</>" : '<fg=yellow>DISABLED</>'];

        // 5. Broadcast
        $rows[] = ['Real-time', 'Reverb', config('reverb') ? '<fg=green>CONFIGURED</>' : '<fg=yellow>NOT CONFIGURED</>'];

        $this->table(['Component', 'Service', 'Status'], $rows);

        $this->newLine();
        $this->info('System check completed at '.now()->toDateTimeString());

        return 0;
    }

    protected function title($text)
    {
        $this->newLine();
        $this->line('<options=bold;bg=blue;fg=white>  '.strtoupper($text).'  </>');
        $this->newLine();
    }
}
