<?php

namespace App\Http\Requests\Api;

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

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

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

        assert($unit instanceof Unit);
        assert($subtype instanceof UnitSubtype);

        return [
            'name' => [
                'sometimes',
                'required',
                'string',
                'max:255',
                Rule::unique(UnitSubtype::class, 'name')
                    ->where('unit_id', $unit->id)
                    ->ignore($subtype),
            ],
        ];
    }

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

        return $data;
    }
}
