<?php

namespace App\Http\Requests\Admin\AcademicClasses;

use App\Enums\AssignmentStatus;
use App\Enums\RegistrationStatus;
use App\Models\Submission;
use Illuminate\Foundation\Http\FormRequest;

class SubmitAssignmentRequest extends FormRequest
{
    public function authorize(): bool
    {
        if (! $this->user()->can('submit-assignments')) {
            return false;
        }

        $student = $this->user()->student;
        $assignment = $this->route('assignment');

        if (! $student || ! $assignment) {
            return false;
        }

        // Whether the assignment still accepts submissions is governed by its
        // status, not the deadline — a lecturer closes it explicitly.
        if ($assignment->status !== AssignmentStatus::Open) {
            return false;
        }

        return $assignment->courseClass()
            ->whereHas('registrations', function ($q) use ($student) {
                $q->where('student_id', $student->id)
                    ->whereHas('submission', fn ($q) => $q->where('status', RegistrationStatus::Approved));
            })
            ->exists();
    }

    public function rules(): array
    {
        $assignment = $this->route('assignment');
        $student = $this->user()->student;

        $hasExistingFile = Submission::query()
            ->where('assignment_id', $assignment->id)
            ->where('student_id', $student?->id)
            ->whereHas('media')
            ->exists();

        return [
            'notes' => ['nullable', 'string'],
            'file' => [
                $hasExistingFile ? 'nullable' : 'required',
                'file',
                'max:10240',
                'mimes:pdf,doc,docx,ppt,pptx,xls,xlsx,jpg,jpeg,png,mp4,zip',
            ],
        ];
    }
}
