<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class StoreVariantRestockRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return auth()->user()?->can('products.restock') ?? false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'quantity' => ['required', 'integer', $this->integerMinRule(1)],
            'notes' => ['nullable', 'string', $this->maxLengthRule(500)],
        ];
    }

    private function integerMinRule(int $min): \Closure
    {
        return static function (string $attribute, mixed $value, \Closure $fail) use ($min): void {
            if ($value === null || $value === '' || filter_var($value, FILTER_VALIDATE_INT) === false) {
                return;
            }

            if ((int) $value < $min) {
                $fail("The {$attribute} must be at least {$min}.");
            }
        };
    }

    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.");
            }
        };
    }
}

