<?php

namespace App\Domain\Training\Services;

use App\Domain\Training\Models\Enrollment;
use App\Domain\Training\Models\TrainingGroup;
use Illuminate\Support\Facades\DB;

class GroupCapacityService
{
    public function refreshCount(TrainingGroup $group): void
    {
        $activeCount = Enrollment::where('training_group_id', $group->id)
            ->where('status', 'active')
            ->count();

        $group->update(['current_count' => $activeCount]);

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

    public function getAvailableSpots(TrainingGroup $group): int
    {
        return max(0, $group->max_capacity - $group->current_count);
    }

    public function hasAvailability(TrainingGroup $group): bool
    {
        return $this->getAvailableSpots($group) > 0 || $group->allow_waitlist;
    }

    public function getWaitlistCount(TrainingGroup $group): int
    {
        return Enrollment::where('training_group_id', $group->id)
            ->where('status', 'waitlisted')
            ->count();
    }

    public function promoteFromWaitlist(TrainingGroup $group): ?Enrollment
    {
        if ($this->getAvailableSpots($group) <= 0) {
            return null;
        }

        $next = Enrollment::where('training_group_id', $group->id)
            ->where('status', 'waitlisted')
            ->orderBy('created_at')
            ->first();

        if ($next) {
            DB::transaction(function () use ($next, $group) {
                $next->update(['status' => 'pending']);
                $this->refreshCount($group);
            });
        }

        return $next;
    }
}
