<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Manage\CourseClassRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\CourseClass;
use App\Services\Admin\Manage\CourseClassService;
use App\Services\Admin\Master\AcademicTermService;
use App\Services\Admin\Master\CourseService;
use App\Services\Admin\Users\LecturerService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class CourseClassController extends Controller
{
    public function __construct(
        private readonly CourseClassService $service,
        private readonly CourseService $courseService,
        private readonly LecturerService $lecturerService,
        private readonly AcademicTermService $academicTermService,
    ) {}

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

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

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Kelas mata kuliah berhasil ditambahkan.']);

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

    public function update(CourseClassRequest $request, CourseClass $courseClass): RedirectResponse
    {
        $this->service->update($courseClass, $request->validated());

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Kelas mata kuliah berhasil diperbarui.']);

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

    public function destroy(CourseClass $courseClass): RedirectResponse
    {
        $this->service->delete($courseClass);

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