<?php
namespace App\Console\Commands;

use App\Http\Controllers\Api\V1\AiController;
use App\Models\PurchaseInvoice;
use App\Models\SalesInvoice;
use App\Models\User;
use App\Notifications\RiskDigest;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Notification;

class RiskDigestCommand extends Command
{
    protected $signature = 'erp:risk-digest';
    protected $description = 'Email + in-app risk digest (AI exception engine) to system administrators';

    public function handle(): int
    {
        $today = Carbon::today();
        $ins = AiController::buildInsights($today);
        $rank = ['Critical' => 0, 'Warning' => 1, 'Watch' => 2, 'Opportunity' => 3];
        $crit = count(array_filter($ins, fn($x) => $x['sev'] === 'Critical'));
        $warn = count(array_filter($ins, fn($x) => $x['sev'] === 'Warning'));
        $opp = count(array_filter($ins, fn($x) => $x['sev'] === 'Opportunity'));
        $t = $today->format('Y-m-d') . ' 00:00:00';
        $atRisk = round(\App\Services\CurrencyService::sumGhs(PurchaseInvoice::where('status', '!=', 'draft')->where('balance_due', '>', 0)->where('due_date', '<', $t), 'balance_due'))
            + round(\App\Services\CurrencyService::sumGhs(SalesInvoice::where('status', '!=', 'draft')->where('balance_due', '>', 0)->where('due_date', '<', $t), 'balance_due'));
        usort($ins, fn($a, $b) => $rank[$a['sev']] <=> $rank[$b['sev']]);
        $digest = [
            'date' => $today->format('d M Y'), 'crit' => $crit, 'warn' => $warn, 'opp' => $opp,
            'atRisk' => $atRisk,
            'top' => array_slice(array_map(fn($x) => ['sev' => $x['sev'], 'title' => $x['title']], $ins), 0, 10),
        ];
        $admins = User::where('is_active', true)->get()->filter(fn($u) =>
            $u->roles()->whereIn('slug', ['super-admin', 'general-manager'])->exists())->values();
        if ($admins->isEmpty()) {
            $this->warn('No super-admin / general-manager users found — digest skipped.');
            return self::SUCCESS;
        }
        Notification::send($admins, new RiskDigest($digest));
        $this->info("Risk digest queued for {$admins->count()} admin(s): $crit critical, $warn warnings, GH₵" . number_format($atRisk) . ' at risk.');
        return self::SUCCESS;
    }
}
