<?php

namespace App\Http\Controllers\Admin\AcademicClasses;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AcademicClasses\AssignmentRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\Assignment;
use App\Services\Admin\AcademicClasses\AssignmentService;
use App\Services\Admin\Manage\CourseClassService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class AssignmentController extends Controller
{
    public function __construct(
        private readonly AssignmentService $service,
        private readonly CourseClassService $courseClassService,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/academic-classes/assignments/index', [
            'assignments' => $this->service->paginated(
                ...$request->validatedWithDefaults(),
                courseClassId: $request->validated('course_class_id'),
            ),
            'courseClasses' => $this->courseClassService->getAllForSelect(),
            'filters' => $request->only(['course_class_id']),
        ]);
    }

    public function store(AssignmentRequest $request): RedirectResponse
    {
        $this->service->create($request->validated(), $request->file('attachment'));

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

        return to_route('admin.academic-classes.assignments.index');
    }

    public function update(AssignmentRequest $request, Assignment $assignment): RedirectResponse
    {
        $this->service->update($assignment, $request->validated(), $request->file('attachment'));

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

        return to_route('admin.academic-classes.assignments.index');
    }

    public function destroy(Assignment $assignment): RedirectResponse
    {
        $this->service->delete($assignment);

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