<?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 StoreUnitSubtypeRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->hasPermission(PermissionSlug::UnitsCreate) === true;
    }

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

        assert($unit instanceof Unit);

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

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

        return [
            'name' => $data['name'],
        ];
    }
}
