<?php

namespace App\Services;

use App\Models\Batch;
use App\Models\User;
use Illuminate\Pagination\LengthAwarePaginator;

class BatchService
{
    public function getAllPaginated(int $perPage = 10): LengthAwarePaginator
    {
        return Batch::with('schoolClass')->orderBy('name')->paginate($perPage);
    }

    public function getByClass($classId): \Illuminate\Database\Eloquent\Collection
    {
        return Batch::where('school_class_id', $classId)->where('is_active', true)->get();
    }

    public function create(array $data): Batch
    {
        return Batch::create($data);
    }

    public function update(Batch $batch, array $data): bool
    {
        return $batch->update($data);
    }

    public function delete(Batch $batch): bool
    {
        return $batch->delete();
    }

    public function toggleStatus(Batch $batch): bool
    {
        return $batch->update(['is_active' => !$batch->is_active]);
    }

    public function assignStudent(Batch $batch, User $student): bool
    {
        if ($batch->current_students >= $batch->capacity) {
            return false;
        }

        $student->update(['batch_id' => $batch->id]);
        $batch->increment('current_students');
        return true;
    }

    public function removeStudent(Batch $batch, User $student): bool
    {
        $student->update(['batch_id' => null]);
        $batch->decrement('current_students');
        return true;
    }
}