<?php

namespace Modules\Academic\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateClassroomRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return $this->user()->hasRole('admin');
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'name' => [
                'required',
                'string',
                'max:100',
                Rule::unique('classrooms', 'name')
                    ->ignore($this->classroom->id)
                    ->where('academic_year_id', $this->academic_year_id)
            ],
            'academic_year_id' => [
                'required',
                'integer',
                'exists:academic_years,id'
            ],
            'capacity' => [
                'required',
                'integer',
                'min:1',
                'max:200'
            ],
            'description' => [
                'nullable',
                'string',
                'max:500'
            ],
            'subject_ids' => [
                'nullable',
                'array'
            ],
            'subject_ids.*' => [
                'integer',
                'exists:subjects,id'
            ],
        ];
    }

    /**
     * Get custom validation messages.
     */
    public function messages(): array
    {
        return [
            'name.required' => 'Please enter the classroom name.',
            'name.unique' => 'A classroom with this name already exists.',
            'academic_year_id.required' => 'Please select an academic year.',
            'academic_year_id.exists' => 'The selected academic year does not exist.',
            'capacity.required' => 'Please enter the classroom capacity.',
            'capacity.min' => 'Classroom capacity must be at least 1.',
            'capacity.max' => 'Classroom capacity cannot exceed 200.',
            'subject_ids.array' => 'Invalid subjects selection.',
            'subject_ids.*.exists' => 'One or more selected subjects do not exist.',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // Check if capacity is not less than current enrollments
            if ($this->capacity) {
                $currentEnrollments = $this->classroom->enrollments()->active()->count();
                if ($this->capacity < $currentEnrollments) {
                    $validator->errors()->add('capacity', "Capacity cannot be less than current enrollments ({$currentEnrollments}).");
                }
            }

            // Validate subject selection
            if ($this->subject_ids) {
                $inactiveSubjects = \Modules\Academic\Models\Subject::whereIn('id', $this->subject_ids)
                    ->where('is_active', false)
                    ->exists();

                if ($inactiveSubjects) {
                    $validator->errors()->add('subject_ids', 'Cannot assign inactive subjects to classroom.');
                }
            }
        });
    }
}
