<?php

namespace App\Services\Admin\AcademicClasses;

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

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

    public function availableStudents(Assignment $assignment): Collection
    {
        return Student::query()
            ->whereHas('enrollments', fn ($q) => $q->where('course_class_id', $assignment->course_class_id))
            ->whereDoesntHave('submissions', fn ($q) => $q->where('assignment_id', $assignment->id))
            ->with(['user.profile', 'department'])
            ->get();
    }

    public function create(Assignment $assignment, array $data, ?UploadedFile $file): Submission
    {
        $submission = $assignment->submissions()->create([
            'student_id' => $data['student_id'],
            'notes' => $data['notes'] ?? null,
            'status' => $data['status'],
            'submitted_at' => $data['submitted_at'] ?? null,
            'score' => $data['score'] ?? null,
            'lecturer_feedback' => $data['lecturer_feedback'] ?? null,
        ]);

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

        return $submission;
    }

    public function update(Submission $submission, array $data, ?UploadedFile $file): Submission
    {
        $submission->notes = $data['notes'] ?? null;
        $submission->status = $data['status'];
        $submission->submitted_at = $data['submitted_at'] ?? null;
        $submission->score = $data['score'] ?? null;
        $submission->lecturer_feedback = $data['lecturer_feedback'] ?? null;
        $submission->update();

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

        return $submission;
    }

    public function delete(Submission $submission): bool
    {
        return $submission->delete();
    }
}
