<?php

namespace App\Http\Requests\Category;

use App\Rules\UniqueCategory;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class CategoryStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => [
                'required',
                new UniqueCategory, // Pass parent_id to the custom rule constructor
            ],
            'image' => 'nullable|image|max:500',
            'type' => 'nullable|string|in:row_product,finish_product',
            'ordering' => 'nullable|integer|min:0',
            'parent_id' => 'nullable',
        ];
    }

    public function failedValidation($validator)
    {
        $errors = $validator->errors();

        throw new HttpResponseException(response()->json(['errors' => $errors], 422));
    }
}
