<?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 App\Mail\SystemHealthDigest;
use App\Models\User;
use App\Services\AI\AiService;
use App\Services\Monitoring\SystemMonitoringService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class SendSystemHealthDigest extends Command
{
    protected $signature = 'system:send-digest';

    protected $description = 'Generate and send AI-powered system health digest to administrators';

    public function __construct(
        protected SystemMonitoringService $monitoringService,
        protected AiService $aiService
    ) {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('Gathering system metrics...');
        $stats = $this->monitoringService->getAll();

        if (! get_setting('ai_enabled', false)) {
            $this->error('AI Service is disabled. Cannot generate analysis.');

            return 1;
        }

        $this->info('Generating AI analysis...');

        $prompt = 'As a Senior Systems Architect, analyze the following system metrics and provide a concise, professional summary of the system health. 
        Detect any issues and provide recommendations.
        
        METRICS:
        '.json_encode($stats, JSON_PRETTY_PRINT);

        $result = $this->aiService->provider()->generate($prompt);

        if (isset($result['success']) && $result['success']) {
            $analysis = $result['response'];

            $admins = User::role(['Developer', 'Administrator'])->get();
            $this->info('Sending digest to '.$admins->count().' administrators...');

            foreach ($admins as $admin) {
                Mail::to($admin->email)->send(new SystemHealthDigest($analysis, $stats));
            }

            $this->info('Digest sent successfully!');
        } else {
            $this->error('AI Analysis failed: '.($result['error'] ?? 'Unknown error'));
        }

        return 0;
    }
}
