import 'package:firebase_auth/firebase_auth.dart';

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  /// 🔥 REGISTER
  Future<User?> register(String email, String password) async {
    try {
      UserCredential user = await _auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      return user.user;
    } on FirebaseAuthException catch (e) {
      throw _handleAuthError(e);
    } catch (e) {
      throw "Terjadi kesalahan saat registrasi";
    }
  }

  /// 🔥 LOGIN
  Future<User?> login(String email, String password) async {
    try {
      UserCredential user = await _auth.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
      return user.user;
    } on FirebaseAuthException catch (e) {
      throw _handleAuthError(e);
    } catch (e) {
      throw "Terjadi kesalahan saat login";
    }
  }

  /// 🔥 LOGOUT
  Future<void> logout() async {
    try {
      await _auth.signOut();
    } catch (e) {
      throw "Gagal logout";
    }
  }

  /// 🔥 RESET PASSWORD (DITAMBAHKAN)
  Future<void> resetPassword(String email) async {
    try {
      await _auth.sendPasswordResetEmail(email: email);
    } on FirebaseAuthException catch (e) {
      throw _handleAuthError(e);
    } catch (e) {
      throw "Gagal mengirim reset password";
    }
  }

  /// 🔥 HANDLE ERROR FIREBASE
  String _handleAuthError(FirebaseAuthException e) {
    switch (e.code) {
      case 'email-already-in-use':
        return "Email sudah digunakan";
      case 'invalid-email':
        return "Format email tidak valid";
      case 'weak-password':
        return "Password terlalu lemah (min 6 karakter)";
      case 'user-not-found':
        return "User tidak ditemukan";
      case 'wrong-password':
        return "Password salah";
      case 'network-request-failed':
        return "Tidak ada koneksi internet";
      default:
        return "Terjadi kesalahan: ${e.message}";
    }
  }
}
