<?php

namespace Modules\Academic\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $examType = $this->route('exam_type');

        return [
            'academic_year_id' => [
                'required',
                'integer',
                'exists:academic_years,id'
            ],
            'name' => [
                'required',
                'string',
                'max:255',
                'unique:exam_types,name,' . $examType->id
            ],
            'description' => [
                'nullable',
                'string',
                'max:500'
            ],
            'weight' => [
                'required',
                'numeric',
                'min:0',
                'max:100'
            ],
            'is_active' => [
                'boolean'
            ],
        ];
    }

    /**
     * Get custom validation messages.
     */
    public function messages(): array
    {
        return [
            'academic_year_id.required' => 'Please select an academic year.',
            'academic_year_id.exists' => 'The selected academic year is invalid.',
            'name.required' => 'Please enter the exam type name.',
            'name.unique' => 'An exam type with this name already exists.',
            'weight.required' => 'Please enter the weight percentage.',
            'weight.min' => 'Weight cannot be negative.',
            'weight.max' => 'Weight cannot exceed 100%.',
            'description.max' => 'Description cannot exceed 500 characters.',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $examType = $this->route('exam_type');

            // Validate weight if provided
            if ($this->weight !== null) {
                // Check if total weight with other exam types in the same academic year would exceed 100%
                $academicYearId = $this->academic_year_id ?? $examType->academic_year_id;

                $totalWeight = \Modules\Academic\Models\ExamType::where('is_active', true)
                    ->where('academic_year_id', $academicYearId)
                    ->where('id', '!=', $examType->id)
                    ->sum('weight');

                // Only add the current weight if the exam type will be active
                $willBeActive = $this->is_active ?? $examType->is_active;

                if ($willBeActive && ($totalWeight + $this->weight) > 100) {
                    $validator->errors()->add('weight', 'Total weight of all active exam types in this academic year cannot exceed 100%.');
                }
            }

            // Check if trying to deactivate exam type with existing results
            if (isset($this->is_active) && !$this->is_active && $examType->is_active) {
                $hasResults = \Modules\Results\Models\Result::where('exam_type_id', $examType->id)
                    ->exists();

                if ($hasResults) {
                    $validator->errors()->add('is_active', 'Cannot deactivate exam type with existing results.');
                }
            }
        });
    }
}
