import { useRouter, useSegments } from "expo-router";
import { onAuthStateChanged } from "firebase/auth";
import { doc, getDoc } from "firebase/firestore";
import { useEffect } from "react";
import { auth, db } from "../firebase_config";
import { useUser } from "./ContextUser";

export function useAuthHandler() {
  const router = useRouter();
  const segments = useSegments();
  const { setUser, setRole } = useUser();

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
      if (!currentUser) {
        setUser(null);
        setRole(null);
        router.replace("/login/login");
        return;
      }

      const userDocRef = doc(db, "user", currentUser.uid);
      const userDoc = await getDoc(userDocRef);

      if (!userDoc.exists()) {
        setUser(null);
        setRole(null);
        router.replace("/login/login");
        return;
      }

      const { role } = userDoc.data();
      setUser(currentUser);
      setRole(role);
      
      // Only redirect if we're on login page
      const inAuthGroup = segments[0] === 'login';
      if (inAuthGroup) {
        router.replace("/(tabs)/home");
      }
    });
    
    return unsubscribe;
  }, []);
}