import 'package:flutter/foundation.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import '../config/supabase_config.dart';

/// Supabase 服务
/// 
/// 负责初始化和管理 Supabase 客户端
class SupabaseService {
  SupabaseService._();

  static bool _initialized = false;

  /// 初始化 Supabase
  /// 
  /// 应该在 main() 函数中调用，确保在 runApp 之前完成
  static Future<void> initialize() async {
    if (_initialized) {
      debugPrint('⚠️ Supabase 已经初始化过了');
      return;
    }

    try {
      await Supabase.initialize(
        url: SupabaseConfig.url,
        anonKey: SupabaseConfig.anonKey,
        debug: SupabaseConfig.debug,
      );
      _initialized = true;
      debugPrint('✅ Supabase 初始化成功');
      debugPrint('   URL: ${SupabaseConfig.url}');
    } catch (e) {
      debugPrint('❌ Supabase 初始化失败: $e');
      rethrow;
    }
  }

  /// 获取 Supabase 客户端实例
  static SupabaseClient get client => Supabase.instance.client;

  /// 获取当前登录用户
  static User? get currentUser => client.auth.currentUser;

  /// 检查用户是否已登录
  static bool get isLoggedIn => currentUser != null;

  /// 获取 Auth 实例
  static GoTrueClient get auth => client.auth;

  /// 获取数据库实例
  static SupabaseQueryBuilder from(String table) => client.from(table);

  /// 获取存储实例
  static SupabaseStorageClient get storage => client.storage;

  /// 获取 Realtime 实例
  static RealtimeClient get realtime => client.realtime;

  /// 获取 Functions 实例
  static FunctionsClient get functions => client.functions;
}
