<?php

namespace App\Services\Admin\AcademicClasses;

use App\Enums\SubmissionStatus;
use App\Models\Assignment;
use App\Models\Student;
use App\Models\Submission;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\UploadedFile;

class SubmissionService
{
    /**
     * Self-service submission by the student themselves: creates their
     * submission for this assignment, or updates it if they already
     * submitted before (e.g. resubmitting).
     */
    public function submitForStudent(Assignment $assignment, Student $student, array $data, ?UploadedFile $file): Submission
    {
        $submission = Submission::query()->updateOrCreate(
            ['assignment_id' => $assignment->id, 'student_id' => $student->id],
            [
                'notes' => $data['notes'] ?? null,
                'status' => SubmissionStatus::Submitted,
                'submitted_at' => now(),
            ],
        );

        if ($file) {
            $submission->addMedia($file)->toMediaCollection('submission_file');
        }

        return $submission;
    }

    public function forAssignment(Assignment $assignment): Collection
    {
        return $assignment->submissions()
            ->with(['student.user.profile', 'student.department'])
            ->latest('created_at')
            ->get();
    }

    public function grade(Submission $submission, ?float $score): Submission
    {
        $submission->score = $score;
        $submission->update();

        return $submission;
    }
}
