import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:em2rp/providers/local_user_provider.dart';

class PermissionGate extends StatelessWidget {
  final Widget child;
  final List<String> requiredPermissions;
  final bool requireAll;
  final Widget? fallback;

  const PermissionGate({
    super.key,
    required this.child,
    required this.requiredPermissions,
    this.requireAll = true,
    this.fallback,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<LocalUserProvider>(
      builder: (context, localUserProvider, _) {
        final currentUser = localUserProvider.currentUser;
        if (currentUser == null) {
          return fallback ?? const SizedBox.shrink();
        }

        final hasPermission = requireAll
            ? hasAllPermissions(localUserProvider, requiredPermissions)
            : hasAnyPermission(localUserProvider, requiredPermissions);

        if (hasPermission) {
          return child;
        }

        return fallback ?? const SizedBox.shrink();
      },
    );
  }

  bool hasAllPermissions(LocalUserProvider provider, List<String> permissions) {
    for (final perm in permissions) {
      if (!provider.hasPermission(perm)) return false;
    }
    return true;
  }

  bool hasAnyPermission(LocalUserProvider provider, List<String> permissions) {
    for (final perm in permissions) {
      if (provider.hasPermission(perm)) return true;
    }
    return false;
  }
}
