<?php

namespace App\Services\Admin\Manage;

use App\Models\ClassEnrollment;
use App\Models\CourseClass;
use App\Models\Student;
use Illuminate\Database\Eloquent\Collection;

class ClassEnrollmentService
{
    public function forClass(CourseClass $courseClass): Collection
    {
        return $courseClass->enrollments()
            ->with(['student.user.profile', 'student.department'])
            ->latest('enrolled_at')
            ->get();
    }

    public function availableStudents(CourseClass $courseClass): Collection
    {
        return Student::query()
            ->where('department_id', $courseClass->course->department_id)
            ->whereDoesntHave('enrollments', fn ($q) => $q->where('course_class_id', $courseClass->id))
            ->with(['user.profile', 'department'])
            ->get();
    }

    public function enrollMany(CourseClass $courseClass, array $studentIds): void
    {
        foreach ($studentIds as $studentId) {
            $courseClass->enrollments()->firstOrCreate(
                ['student_id' => $studentId],
                ['enrolled_at' => now()],
            );
        }
    }

    public function unenroll(ClassEnrollment $enrollment): bool
    {
        return $enrollment->delete();
    }
}
