<?php

namespace App\Console\Commands;

use App\Domain\Training\Models\Enrollment;
use App\Domain\Training\Models\TrainingGroup;
use Illuminate\Console\Command;

class ReconcileGroupCounts extends Command
{
    protected $signature = 'groups:reconcile-counts';
    protected $description = 'Reconcile group current_count with actual active enrollments';

    public function handle(): int
    {
        $groups = TrainingGroup::whereIn('status', ['active', 'full', 'forming'])->get();
        $fixed = 0;

        foreach ($groups as $group) {
            $actualCount = Enrollment::where('training_group_id', $group->id)
                ->where('status', 'active')
                ->count();

            if ($group->current_count !== $actualCount) {
                $this->warn("{$group->name_ar}: {$group->current_count} → {$actualCount}");
                $group->update(['current_count' => $actualCount]);

                if ($actualCount >= $group->max_capacity && $group->status === 'active') {
                    $group->update(['status' => 'full']);
                } elseif ($actualCount < $group->max_capacity && $group->status === 'full') {
                    $group->update(['status' => 'active']);
                }

                $fixed++;
            }
        }

        $this->info("Reconciled {$fixed} groups out of {$groups->count()} checked.");
        return self::SUCCESS;
    }
}
