<?php

namespace App\Http\Controllers\Admin\AcademicClasses;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AcademicClasses\SubmissionRequest;
use App\Models\Assignment;
use App\Models\Submission;
use App\Services\Admin\AcademicClasses\SubmissionService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class SubmissionController extends Controller
{
    public function __construct(
        private readonly SubmissionService $service,
    ) {}

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

        return Inertia::render('admin/academic-classes/assignments/submissions', [
            'assignment' => $assignment,
            'submissions' => $this->service->forAssignment($assignment),
            'availableStudents' => $this->service->availableStudents($assignment),
        ]);
    }

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

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

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

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

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

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