<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateBrandRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->check();
    }

    public function rules(): array
    {
        $brandId = $this->route('brand')->id ?? null;

        return [
            'name' => [
                'required',
                'string',
                $this->maxLengthRule(255),
                Rule::unique('brands', 'name')->ignore($brandId),
            ],
            'slug' => [
                'nullable',
                'string',
                $this->maxLengthRule(191),
                Rule::unique('brands', 'slug')->ignore($brandId),
            ],
            'logo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,gif,webp', $this->maxFileKilobytesRule(2048)],
            'is_active' => 'nullable|boolean',
        ];
    }

    public function messages(): array
    {
        return [
            'name.required' => 'Brand name is required.',
            'name.unique' => 'A brand with this name already exists.',
            'slug.unique' => 'A brand with this slug already exists.',
            'logo.image' => 'Logo must be an image file.',
            'logo.max_file' => 'Logo size must not exceed 2MB.',
        ];
    }

    private function maxLengthRule(int $max): \Closure
    {
        return static function (string $attribute, mixed $value, \Closure $fail) use ($max): void {
            if ($value === null || $value === '') {
                return;
            }

            if (!is_string($value)) {
                return;
            }

            if (mb_strlen($value) > $max) {
                $fail("The {$attribute} field must not exceed {$max} characters.");
            }
        };
    }

    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;
            }

            $sizeBytes = $value->getSize() ?: 0;
            if ($sizeBytes > ($maxKb * 1024)) {
                $fail('Logo size must not exceed 2MB.');
            }
        };
    }
}
