<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Manage\CourseRegistrationRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\CourseRegistration;
use App\Services\Admin\Manage\CourseClassService;
use App\Services\Admin\Manage\CourseRegistrationService;
use App\Services\Admin\Master\AcademicTermService;
use App\Services\Admin\Users\LecturerService;
use App\Services\Admin\Users\StudentService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class CourseRegistrationController extends Controller
{
    public function __construct(
        private readonly CourseRegistrationService $service,
        private readonly StudentService $studentService,
        private readonly AcademicTermService $academicTermService,
        private readonly CourseClassService $courseClassService,
        private readonly LecturerService $lecturerService,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/manage/course-registrations/index', [
            'registrations' => $this->service->paginated(
                ...$request->validatedWithDefaults(),
                status: $request->validated('status'),
                academicTermId: $request->validated('academic_term_id'),
            ),
            'students' => $this->studentService->getAllForSelect(),
            'academicTerms' => $this->academicTermService->getAllForSelect(),
            'courseClasses' => $this->courseClassService->getAllForSelect(),
            'lecturers' => $this->lecturerService->getAllForSelect(),
            'filters' => $request->only(['status', 'academic_term_id']),
        ]);
    }

    public function store(CourseRegistrationRequest $request): RedirectResponse
    {
        $this->service->create($request->validated());

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Registrasi KRS berhasil ditambahkan.']);

        return to_route('admin.manage.course-registrations.index');
    }

    public function update(CourseRegistrationRequest $request, CourseRegistration $courseRegistration): RedirectResponse
    {
        $this->service->update($courseRegistration, $request->validated());

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Registrasi KRS berhasil diperbarui.']);

        return to_route('admin.manage.course-registrations.index');
    }

    public function destroy(CourseRegistration $courseRegistration): RedirectResponse
    {
        $this->service->delete($courseRegistration);

        return Inertia::flash('toast', ['type' => 'success', 'message' => 'Registrasi KRS berhasil dihapus.'])->back();
    }
}
