<?php

namespace Daylight\Core\Http\Requests\Store\Attributes;

use Illuminate\Foundation\Http\FormRequest;

class StoreAttributeRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->check() && auth()->user()->can('create:attributes');
    }

    public function rules(): array
    {
        return [
            'parent_id' => ['nullable', 'exists:categories,id'],
            'order' => ['required', 'integer'],
            'key' => ['required', 'string', 'max:255', 'unique:attributes,key'],
            'categories' => ['nullable', 'array'],
            'categories.*' => ['exists:categories,id'],
            'filterable' => ['required', 'boolean'],
            'visible' => ['required', 'boolean'],
            'translations' => ['required', 'array'],
            'translations.*.name' => ['required', 'string', 'max:255'],
            'values' => ['required', 'array'],
            'values.*.id' => ['nullable', 'exists:attribute_values,id'],
            'values.*.translations' => ['required', 'array'],
            'values.*.translations.*.name' => ['required', 'string', 'max:255'],
        ];
    }

    public function prepareForValidation(): void
    {
        $this->merge([
            'key' => strtoupper(str_replace(' ', '_', $this->key)),
        ]);
    }
}
