<?php

namespace App\Modules\Inventory\Requests;

use App\Modules\Inventory\Models\InventoryAttribute;
use App\Modules\Inventory\Support\InventoryAttributeType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreInventoryAttributeRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('create', InventoryAttribute::class) ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $tenantId = $this->user()?->tenant_id;
        $types = array_map(static fn (InventoryAttributeType $t) => $t->value, InventoryAttributeType::cases());

        return [
            'code' => [
                'required',
                'string',
                'max:120',
                Rule::unique('inventory_attributes', 'code')->where(
                    static fn ($q) => $q->where('tenant_id', $tenantId),
                ),
            ],
            'name' => ['required', 'string', 'max:255'],
            'type' => ['required', 'string', Rule::in($types)],
            'options' => ['nullable', 'array'],
            'options.*.value_key' => ['nullable', 'string', 'max:120'],
            'options.*.label' => ['nullable', 'string', 'max:255'],
        ];
    }
}
