<?php

namespace App\Http\Requests\AttendanceCommentTemplate;

use App\Http\Requests\ApiFormRequest;

class UpdateAttendanceCommentTemplateRequest extends ApiFormRequest
{
    public function authorize(): bool
    {
        return true; // add auth/policy if needed
    }

    public function rules(): array
    {
        return [
            'min_score' => ['sometimes', 'integer', 'min:0', 'max:100'],
            'max_score' => ['sometimes', 'integer', 'min:0', 'max:100'],
            'template_text' => ['sometimes', 'string', 'max:5000'],
            'is_active' => ['sometimes', 'boolean'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $min = $this->has('min_score') ? (int) $this->input('min_score') : null;
            $max = $this->has('max_score') ? (int) $this->input('max_score') : null;

            // If both provided, validate relation
            if ($min !== null && $max !== null && $max < $min) {
                $validator->errors()->add('max_score', 'The max_score field must be greater than or equal to min_score.');
            }
        });
    }

    protected function prepareForValidation(): void
    {
        if ($this->has('is_active')) {
            $this->merge([
                'is_active' => filter_var($this->input('is_active'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
                    ?? $this->input('is_active'),
            ]);
        }
    }
}
