import 'package:supabase_flutter/supabase_flutter.dart';

/// Call after sign-in and on app start to enforce app-level profile lock.
/// If the user's `profiles.is_locked` flag is true, this signs out the user.
Future<void> enforceLockForCurrentUser(SupabaseClient supabase) async {
  final current = supabase.auth.currentUser;
  if (current == null) return;

  try {
    // Fetch the authoritative user record from the auth API and inspect
    // `banned_until`. This is the canonical source after an admin `set_lock`.
    final resp = await supabase.auth.getUser();
    final user = resp.user;
    if (user == null) return;

    dynamic bannedRaw;
    try {
      // Support multiple SDK shapes: `bannedUntil`, `banned_until`, or rawData
      bannedRaw =
          (user as dynamic).bannedUntil ??
          (user as dynamic).rawData?['banned_until'] ??
          (user as dynamic).banned_until;
    } catch (_) {
      bannedRaw = null;
    }

    DateTime? bannedUntil;
    if (bannedRaw is String) {
      bannedUntil = DateTime.tryParse(bannedRaw);
    } else if (bannedRaw is DateTime) {
      bannedUntil = bannedRaw;
    }

    if (bannedUntil != null && bannedUntil.isAfter(DateTime.now())) {
      await supabase.auth.signOut();
    }
  } catch (_) {
    // swallow; enforcement is best-effort on the client
  }
}
