<?php

namespace App\Http\Requests\Admin\Manage;

use App\Enums\OrderStatus;
use App\Models\Order;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class OrderStatusTransitionRequest extends FormRequest
{
    public function authorize(): bool
    {
        $status = OrderStatus::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(OrderStatus::class)],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'status' => 'status',
        ];
    }

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

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

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