"use client";

import { createContext, useContext, useState, useEffect } from "react";
import { account,databases,DATABASE_ID,USERS_COLLECTION_ID,Query } from "../lib/appwrite";
import { useRouter } from "next/navigation";

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [userRole, setUserRole] = useState("");
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const session = await account.get(); // Get user session
        setIsAuthenticated(true);

        const userId = session.$id; // Appwrite auth user ID

        // ✅ Fetch custom user data from your collection
        const userData = await databases.listDocuments(
          DATABASE_ID,
          USERS_COLLECTION_ID,
          [Query.equal("userId", userId)]
        );

        const userDoc = userData.documents[0];

        if (userDoc) {
          setUser(userDoc);
          setUserRole(userDoc.role || "user");
        } else {
          console.warn("User document not found in DB.");
        }
      } catch (error) {
        console.error("Auth Error:", error);
        if (error.code === 401) {
          localStorage.removeItem("isLoggedIn");
          setIsAuthenticated(false);
          router.push("/signup");
        }
      } finally {
        setLoading(false);
      }
    };

    checkAuth();
  }, [router]);

  return (
    <AuthContext.Provider
      value={{
        isAuthenticated,
        setIsAuthenticated,
        loading,
        userRole,
        user,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);
