<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Manage\ClassEnrollmentRequest;
use App\Models\ClassEnrollment;
use App\Models\CourseClass;
use App\Services\Admin\Manage\ClassEnrollmentService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class ClassEnrollmentController extends Controller
{
    public function __construct(
        private readonly ClassEnrollmentService $service,
    ) {}

    public function index(CourseClass $courseClass): Response
    {
        $courseClass->load(['course', 'lecturer.user.profile', 'academicTerm']);

        return Inertia::render('admin/manage/course-classes/enrollments', [
            'courseClass' => $courseClass,
            'enrollments' => $this->service->forClass($courseClass),
            'availableStudents' => $this->service->availableStudents($courseClass),
        ]);
    }

    public function store(ClassEnrollmentRequest $request, CourseClass $courseClass): RedirectResponse
    {
        $this->service->enrollMany($courseClass, $request->validated('student_ids'));

        return Inertia::flash('toast', ['type' => 'success', 'message' => 'Mahasiswa berhasil ditambahkan ke kelas.'])->back();
    }

    public function destroy(CourseClass $courseClass, ClassEnrollment $enrollment): RedirectResponse
    {
        $this->service->unenroll($enrollment);

        return Inertia::flash('toast', ['type' => 'success', 'message' => 'Mahasiswa berhasil dikeluarkan dari kelas.'])->back();
    }
}
