import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:google_sign_in/google_sign_in.dart';

///谷歌授权登录
class SCGoogleAuthService {
  static final GoogleSignIn _g = GoogleSignIn(scopes: ['email', 'profile'],);

  // 获取当前用户
  static User? get currentUser => FirebaseAuth.instance.currentUser;

  // 检查登录状态
  static bool get isSignedIn => currentUser != null;

  // 初始化Firebase
  static Future<void> initialize() async {
    await Firebase.initializeApp();
  }

  // 谷歌登录
  static Future<User?> signInWithGoogle() async {
    try {
      // 触发谷歌登录
      final GoogleSignInAccount? googleAccount = await _g.signIn();
      if (googleAccount == null) return null;

      // 获取认证信息
      final GoogleSignInAuthentication googleAuth = await googleAccount.authentication;

      // 创建Firebase凭证
      final OAuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      // 使用凭证登录Firebase
      final UserCredential userCredential =
      await FirebaseAuth.instance.signInWithCredential(credential);

      return userCredential.user;
    } catch (e) {
      print('Google sign-in error: $e');
      rethrow; // 抛出异常让调用者处理
    }
  }

  // 静默登录（检查现有会话）
  static Future<User?> signInSilently() async {
    try {
      // 尝试静默登录
      final GoogleSignInAccount? googleAccount =
      await _g.signInSilently();

      if (googleAccount == null) return null;

      // 获取认证信息
      final GoogleSignInAuthentication googleAuth =
      await googleAccount.authentication;

      // 创建Firebase凭证
      final OAuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      // 使用凭证登录Firebase
      final UserCredential userCredential =
      await FirebaseAuth.instance.signInWithCredential(credential);

      return userCredential.user;
    } catch (e) {
      print('Silent sign-in error: $e');
      return null;
    }
  }

  // 登出
  static Future<void> signOut() async {
    try {
      await _g.signOut();
      await FirebaseAuth.instance.signOut();
    } catch (e) {
      print('Sign out error: $e');
      rethrow;
    }
  }

  // 获取用户信息
  static Map<String, dynamic>? getUserInfo() {
    final user = currentUser;
    if (user == null) return null;

    return {
      'uid': user.uid,
      'name': user.displayName,
      'email': user.email,
      'photoUrl': user.photoURL,
      'isEmailVerified': user.emailVerified,
    };
  }
}