<?php

namespace App\Http\Middleware;

use App\Services\Subscriptions\SubscriptionService;
use App\Services\Tenancy\CurrentBusiness;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsurePlanFeature
{
    public function handle(Request $request, Closure $next, string $feature): Response
    {
        if ($request->user()?->isSuperAdmin()) {
            return $next($request);
        }

        $business = app(CurrentBusiness::class)->get();

        if (! $business) {
            abort(403, 'No business workspace is assigned to this account.');
        }

        if (! app(SubscriptionService::class)->hasFeature($business, $feature)) {
            if ($request->expectsJson()) {
                abort(403, 'This feature is not available on the current plan.');
            }

            return redirect()
                ->route('admin.subscription.upgrade')
                ->with('status', 'Upgrade your plan to use this feature.');
        }

        return $next($request);
    }
}
