<?php

namespace App\Http\Requests\Api;

use App\Enums\PermissionSlug;
use App\Models\Floor;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateFloorRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->hasPermission(PermissionSlug::UnitsUpdate) === true;
    }

    /**
     * @return array<string, ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $floor = $this->route('floor');

        assert($floor instanceof Floor);

        return [
            'name' => [
                'sometimes',
                'required',
                'string',
                'max:50',
                Rule::unique(Floor::class, 'name')->ignore($floor),
            ],
            'sort_order' => ['sometimes', 'required', 'integer', 'min:0', 'max:1000'],
        ];
    }

    /**
     * @return array{name?: string, sort_order?: int}
     */
    public function payload(): array
    {
        /** @var array{name?: string, sort_order?: mixed} $data */
        $data = $this->safe()->only(['name', 'sort_order']);

        if (array_key_exists('sort_order', $data)) {
            $data['sort_order'] = (int) $data['sort_order'];
        }

        return $data;
    }
}
