<?php

namespace App\Console\Commands;

use App\Domain\Training\Models\TrainingGroup;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class AlertFullGroups extends Command
{
    protected $signature = 'groups:alert-capacity {--threshold=90 : Percentage threshold}';
    protected $description = 'Alert admins about groups nearing capacity';

    public function handle(): int
    {
        $threshold = (int) $this->option('threshold');
        $alerts = [];

        $groups = TrainingGroup::where('status', 'active')
            ->where('max_capacity', '>', 0)
            ->get();

        foreach ($groups as $group) {
            $percentage = round(($group->current_count / $group->max_capacity) * 100);

            if ($percentage >= $threshold) {
                $alerts[] = [
                    'group' => $group->name_ar,
                    'capacity' => "{$group->current_count}/{$group->max_capacity}",
                    'percentage' => $percentage,
                ];
            }
        }

        if (empty($alerts)) {
            $this->info("No groups at {$threshold}%+ capacity.");
            return self::SUCCESS;
        }

        $this->table(['المجموعة', 'السعة', 'النسبة%'], array_map(fn ($a) => [$a['group'], $a['capacity'], $a['percentage'] . '%'], $alerts));

        Log::channel('daily')->info("Groups nearing capacity ({$threshold}%+)", ['groups' => $alerts]);
        $this->info(count($alerts) . " groups at {$threshold}%+ capacity.");

        return self::SUCCESS;
    }
}
