<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        $categoryId = $this->route('category') ? $this->route('category')->id : null;
        $parentId = $this->input('parent_id');

        return [
            'name' => [
                'required',
                'string',
                'max:255',
                function ($attribute, $value, $fail) use ($parentId, $categoryId) {
                    $exists = \App\Models\Category::where('name', $value)
                        ->where('parent_id', $parentId)
                        ->when($categoryId, function ($q) use ($categoryId) {
                            return $q->where('id', '!=', $categoryId);
                        })
                        ->exists();

                    if ($exists) {
                        $fail('The category name already exists under the selected parent.');
                    }
                },
            ],
            'parent_id' => 'nullable|exists:categories,id',
            'status' => 'nullable|boolean',
        ];
    }
}
