<?php

declare(strict_types=1);

namespace App\Http\Requests\Asset;

use App\Enums\AssetStatus;
use App\Models\Asset;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

/**
 * A single, deliberate status transition — never a free-form field edit.
 *
 * The legality check is duplicated on purpose: it runs here, so the form
 * shows a normal validation error next to the field the user just touched,
 * and again inside AssetService::changeStatus(), so the rule still holds for
 * any future caller (a console command, a bulk action) that skips this
 * request entirely.
 */
class UpdateAssetStatusRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'status' => ['required', Rule::enum(AssetStatus::class)],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            $target = AssetStatus::tryFrom((string) $this->input('status'));

            if ($target === null) {
                return;
            }

            $asset = $this->targetAsset();

            if (! $asset->status->canTransitionTo($target)) {
                $validator->errors()->add('status', __(':from cannot move directly to :to.', [
                    'from' => $asset->status->label(),
                    'to' => $target->label(),
                ]));
            }
        });
    }

    public function targetAsset(): Asset
    {
        /** @var Asset $asset */
        $asset = $this->route('asset');

        return $asset;
    }
}
