<?php

namespace App\Http\Middleware;

use App\Services\Care\OrganizationResolver;
use App\Services\Care\PlanService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Blocks free-plan accounts from Pro modules (lab, pharmacy, billing, service queues).
 */
class EnsurePaidPlan
{
    public function __construct(
        protected OrganizationResolver $organizations,
        protected PlanService $plans,
    ) {}

    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        if (! $user) {
            return $next($request);
        }

        $organization = $this->organizations->resolveForUser($user);
        if (! $organization || $this->plans->hasPaidPlan($organization)) {
            return $next($request);
        }

        if ($request->expectsJson() || $request->ajax()) {
            return response()->json([
                'message' => 'This feature requires Care Pro or Enterprise.',
                'upgrade_url' => route('care.pro.index'),
            ], 402);
        }

        return redirect()
            ->route('care.pro.index')
            ->with('upsell', 'Lab, pharmacy, billing, and in-app service queues are part of Care Pro. Upgrade to unlock them.');
    }
}
