<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreCategoryRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    protected function prepareForValidation(): void
    {
        // Coerce the gemstone checkbox to a boolean so the rule accepts it
        // whether the form sends '1', 'true', or omits it entirely.
        $this->merge([
            'is_gemstone' => $this->boolean('is_gemstone'),
        ]);
    }

    public function rules(): array
    {
        return [
            'name' => [
                'required',
                'string',
                'max:150',
                Rule::unique('categories', 'name')->whereNull('deleted_at'),
            ],
            'code' => [
                'required',
                'string',
                'max:50',
                'regex:/^[A-Za-z0-9_]+$/',
                Rule::unique('categories', 'code')->whereNull('deleted_at'),
            ],
            // parent_id removed — categories are a flat, single-level list.
            'description'   => ['nullable', 'string', 'max:1000'],
            'display_order' => ['nullable', 'integer', 'min:0', 'max:99999'],
            'status'        => ['required', 'boolean'],
            'is_gemstone'   => ['nullable', 'boolean'],
            'image'         => ['nullable', 'image', 'mimes:jpg,jpeg,png', 'max:2048'],
        ];
    }

    public function messages(): array
    {
        return [
            'name.unique'      => 'Category name already exists.',
            'code.unique'      => 'Category code already exists.',
            'code.regex'       => 'Category code may only contain letters, numbers, and underscores (no spaces).',
            'image.max'        => 'The image must not be larger than 2 MB.',
            'image.mimes'      => 'The image must be a JPG or PNG file.',
        ];
    }

    public function attributes(): array
    {
        return [
            'name'          => 'Category Name',
            'code'          => 'Category Code',
            'display_order' => 'Display Order',
            'is_gemstone'   => 'Gemstone Category',
            'image'         => 'Category Image',
        ];
    }
}
