<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Symfony\Component\HttpFoundation\Response;

final class BindCurrentMerchant
{
    public function handle(Request $request, Closure $next): Response
    {
        $merchant = $request->attributes->get('merchant') ?? $request->user();
        if ($merchant) {
            App::instance('currentMerchant', $merchant);
        }
        try {
            return $next($request);
        } finally {
            App::forgetInstance('currentMerchant');
        }
    }
}
