<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

/**
 * Gate any route behind a boolean feature flag set by the platform super-admin
 * on the organisation's meta.features configuration.
 *
 * Usage in routes:
 *   Route::middleware(['org-feature:pos'])->group(...)
 *
 * Supported feature keys (must match the keys in meta.features and
 * the DEFAULT_FEATURES constant in Organizations.vue):
 *   pos, reports, inventory, customers, expenses, api_access
 *
 * The super-admin and platform-admin users are always allowed through
 * (they are not constrained by org-level feature flags).
 * If an org has no meta.features configured, all features default to enabled.
 */
class CheckOrgFeature
{
    public function handle(Request $request, Closure $next, string $feature): mixed
    {
        $user = $request->user();

        // Unauthenticated → let the auth middleware handle it
        if (! $user) {
            return $next($request);
        }

        // Platform-level admins bypass all org-feature gates
        if ($user->is_platform_admin || $user->hasRole('super-admin')) {
            return $next($request);
        }

        // Users without an org (shouldn't happen in normal flow, but guard anyway)
        if (! $user->organization_id) {
            return $next($request);
        }

        $org      = $user->organization ?? $user->load('organization')->organization;
        $features = $org?->getOrgFeatures() ?? [];

        // Default: enabled. Block only when explicitly set to false.
        if (isset($features[$feature]) && ! $features[$feature]) {
            return response()->json([
                'message' => 'This feature has been disabled for your organisation by the platform administrator.',
                'feature' => $feature,
                'blocked' => true,
            ], 403);
        }

        return $next($request);
    }
}
