<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class UpdateAttributeRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return auth()->user()->can('products.update') || auth()->user()->isAdmin();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $attribute = $this->route('attribute');
        $attributeId = is_object($attribute) ? $attribute->id : $attribute;
        
        return [
            'name' => ['required', 'string', $this->maxLengthRule(255), 'unique:attributes,name,' . $attributeId],
            'status' => 'required|in:active,inactive',
        ];
    }

    private function maxLengthRule(int $max): \Closure
    {
        return static function (string $attribute, mixed $value, \Closure $fail) use ($max): void {
            if (is_string($value) && mb_strlen($value) > $max) {
                $fail("The {$attribute} field must not exceed {$max} characters.");
            }
        };
    }
}
