<?php

namespace App\Http\Controllers\Admin\Master;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Master\CourseRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\Course;
use App\Services\Admin\Master\CourseService;
use App\Services\Admin\Master\DepartmentService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class CourseController extends Controller
{
    public function __construct(
        private readonly CourseService $service,
        private readonly DepartmentService $departmentService,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/master/courses/index', [
            'courses' => $this->service->paginated(
                ...$request->validatedWithDefaults(),
                departmentId: $request->validated('department_id'),
                semesterNumber: $request->validated('semester_number'),
            ),
            'departments' => $this->departmentService->getAllForSelect(),
            'semesterNumbers' => $this->service->getSemesterNumbers(),
            'filters' => $request->only(['department_id', 'semester_number']),
        ]);
    }

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

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

        return to_route('admin.master.courses.index');
    }

    public function update(CourseRequest $request, Course $course): RedirectResponse
    {
        $this->service->update($course, $request->validated());

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

        return to_route('admin.master.courses.index');
    }

    public function destroy(Course $course): RedirectResponse
    {
        $this->service->delete($course);

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