import 'package:get/get.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../../../routes/app_pages.dart';

class SplashScreenController extends GetxController {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  @override
  void onInit() {
    super.onInit();
    _checkAuthStatus();
  }

  void _checkAuthStatus() async {
    await Future.delayed(const Duration(seconds: 4));

    User? user = _auth.currentUser;

    if (user != null) {
      try {
        final userDoc = await _firestore
            .collection('users')
            .doc(user.uid)
            .get();

        if (userDoc.exists) {
          final userData = userDoc.data()!;
          final deviceId = userData['device_id'] as String?;
          final userName = userData['name'] as String? ?? 'User';

          if (deviceId != null && deviceId.isNotEmpty) {
            Get.offAllNamed(
              Routes.HOME_PATIENT,
              arguments: {
                'deviceId': deviceId,
                'userName': userName,
                'userEmail': user.email ?? '',
              },
            );
          } else {
            await _auth.signOut();
            Get.offAllNamed(Routes.LOGIN);
          }
        } else {
          Get.offAllNamed(Routes.NAVBAR);
        }
      } catch (e) {
        print('Error checking user data: $e');
        await _auth.signOut();
        Get.offAllNamed(Routes.LOGIN);
      }
    } else {
      Get.offAllNamed(Routes.LOGIN);
    }
  }
}
