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

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  // 구글 로그인
  Future<UserCredential?> signInWithGoogle() async {
    // 1. 구글 로그인 흐름 시작
    print('[DEBUG] Google Sign-In: Starting signIn()');
    final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
    print(
      '[DEBUG] Google Sign-In: signIn() completed, user: ${googleUser?.email}',
    );

    if (googleUser == null) {
      // 사용자가 로그인 창을 닫음
      print('[DEBUG] Google Sign-In: User canceled');
      return null;
    }

    // 2. 인증 세부 정보 요청
    print('[DEBUG] Google Sign-In: Getting authentication...');
    final GoogleSignInAuthentication googleAuth =
        await googleUser.authentication;
    print(
      '[DEBUG] Google Sign-In: Authentication received. AccessToken: ${googleAuth.accessToken != null}, IDToken: ${googleAuth.idToken != null}',
    );

    // 3. 자격 증명 생성
    final OAuthCredential credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    // 4. Firebase에 로그인
    print('[DEBUG] Google Sign-In: Signing in with credential to Firebase...');
    final userCredential = await _auth.signInWithCredential(credential);
    print(
      '[DEBUG] Google Sign-In: Firebase sign-in completed. User: ${userCredential.user?.uid}',
    );
    return userCredential;
  }

  // 로그아웃
  Future<void> signOut() async {
    await _googleSignIn.signOut();
    await _auth.signOut();
  }
}
