<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class StoreCategoryRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->user()->can('categories.create') || auth()->user()->isAdmin();
    }

    public function rules(): array
    {
        return [
            'parent_id' => 'nullable|exists:categories,id',
            'name' => ['required', 'string', $this->maxLengthRule(255)],
            'description' => 'nullable|string|max:20000',
            'meta_title' => ['nullable', 'string', $this->maxLengthRule(255)],
            'meta_description' => ['nullable', 'string', $this->maxLengthRule(500)],
            'image' => ['nullable', 'image', 'mimes:jpeg,png,jpg,gif,webp', $this->maxFileKilobytesRule(2048)],
            'is_active' => 'nullable|boolean',
            'sort_order' => ['nullable', 'integer', $this->integerMinRule(0)],
        ];
    }

    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.");
            }
        };
    }

    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 maxFileKilobytesRule(int $maxKb): \Closure
    {
        return static function (string $attribute, mixed $value, \Closure $fail) use ($maxKb): void {
            if (!$value instanceof \Illuminate\Http\UploadedFile) {
                return;
            }

            if (($value->getSize() ?: 0) > ($maxKb * 1024)) {
                $fail("The {$attribute} field must not exceed {$maxKb} KB.");
            }
        };
    }
}
