<?php

namespace App\Modules\Core\Middleware;

use App\Http\Responses\ApiResponse;
use App\Modules\Subscription\Models\Feature;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureFeatureAccess
{
    /**
     * @param Closure(Request): Response $next
     */
    public function handle(Request $request, Closure $next, string $feature): Response
    {
        $company = $request->attributes->get('currentCompany');

        if (! $company) {
            return ApiResponse::error('Company context is required', 422);
        }

        $subscription = $company->activeSubscription()
            ->with('plan.features')
            ->first();

        if (! $subscription || ! $subscription->plan || ! $subscription->plan->is_active) {
            return ApiResponse::error('This module requires an active subscription', 403);
        }

        $hasFeature = $subscription->plan->features->contains(
            fn (Feature $planFeature): bool => $planFeature->slug === $feature && $planFeature->is_active
        );

        if (! $hasFeature) {
            return ApiResponse::error('This module is not enabled on the current plan', 403);
        }

        return $next($request);
    }
}
