<?php

namespace App\Http\Requests\SelfPaced;

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

/**
 * UpdateTopicTimingRequest
 *
 * Validates topic timing configuration (min and max time in minutes).
 *
 * Requirements: 3.4, 3.9
 */
class UpdateTopicTimingRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('manage self-paced settings');
    }

    public function rules(): array
    {
        return [
            'min_time_minutes' => ['nullable', 'integer', 'min:0'],
            'max_time_minutes' => ['nullable', 'integer', 'min:0'],
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $minTime = (int)($this->input('min_time_minutes') ?? 0);
            $maxTime = (int)($this->input('max_time_minutes') ?? 0);

            // Both must be null or both must satisfy min <= max
            if ($minTime > 0 && $maxTime > 0 && $maxTime < $minTime) {
                $validator->errors()->add('max_time_minutes', 'Maximum time must be greater than or equal to minimum time');
            }
        });
    }

    public function messages(): array
    {
        return [
            'min_time_minutes.integer' => 'Minimum time must be a whole number',
            'min_time_minutes.min' => 'Minimum time cannot be negative',
            'max_time_minutes.integer' => 'Maximum time must be a whole number',
            'max_time_minutes.min' => 'Maximum time cannot be negative',
        ];
    }
}
