<?php

namespace App\Http\Requests\Admin\Manage;

use App\Enums\CuttingStatus;
use App\Models\Cutting;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class CuttingStatusTransitionRequest extends FormRequest
{
    public function authorize(): bool
    {
        $status = CuttingStatus::tryFrom((string) $this->input('status'));

        if ($status === null) {
            return false;
        }

        try {
            $permission = $status->transitionPermission();
        } catch (\InvalidArgumentException) {
            return false;
        }

        return $this->user()?->can($permission->value) ?? false;
    }

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

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            /** @var Cutting $cutting */
            $cutting = $this->route('cutting');
            $status = CuttingStatus::tryFrom((string) $this->input('status'));

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

            if (! $cutting->status->canTransitionTo($status)) {
                $validator->errors()->add('status', 'Status cutting tidak dapat diubah.');
            }
        });
    }
}
