<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Services\OrderStatusTransitionService;
use App\Models\Order;

class ValidateOrderStatusTransition
{
    public function handle(Request $request, Closure $next)
    {
        if ($request->has('status') && $request->route('order')) {
            $order = $request->route('order');
            $newStatus = $request->input('status');
            
            // Skip validation for force updates
            if ($request->has('force') && $request->input('force')) {
                return $next($request);
            }
            
            $validation = OrderStatusTransitionService::validateTransition($order, $newStatus);
            
            if (!$validation['valid']) {
                return response()->json([
                    'success' => false,
                    'message' => $validation['message'],
                    'allowed_transitions' => OrderStatusTransitionService::getAllowedTransitions($order->status)
                ], 422);
            }
        }
        
        return $next($request);
    }
}