<?php

namespace App\Http\Controllers\Admin\AcademicClasses;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AcademicClasses\GradeSubmissionRequest;
use App\Http\Requests\Admin\AcademicClasses\SubmitAssignmentRequest;
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
    {
        $this->abortUnlessLecturerOwnsAssignment($assignment);

        $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),
        ]);
    }

    public function grade(GradeSubmissionRequest $request, Assignment $assignment, Submission $submission): RedirectResponse
    {
        $this->service->grade($submission, $request->validated('score'));

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

    public function submit(SubmitAssignmentRequest $request, Assignment $assignment): RedirectResponse
    {
        $this->service->submitForStudent($assignment, $request->user()->student, $request->validated(), $request->file('file'));

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

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

    /**
     * A dosen may only manage submissions for classes they lecture.
     */
    private function abortUnlessLecturerOwnsAssignment(Assignment $assignment): void
    {
        $user = request()->user();

        abort_if(
            $user->hasRole('dosen') && $assignment->courseClass?->lecturer_id !== $user->lecturer?->id,
            403,
        );
    }
}
