import FirebaseQuery from "../../firebase/firebaseQuery";
import {orderBy, limit, arrayUnion} from "firebase/firestore";
import {useState}  from "react";
import { UserData } from "../../typeDefinitions";

export function useUpdates({user}: {user: UserData}){
   const [active, setActive] = useState<{title: string, body: string, id: string}>();
   const firebaseQuery = new FirebaseQuery();

   const fetchUpdates = async () => {
    try {
        const docs = await firebaseQuery.getDocsWhere("updates", [orderBy("created", "desc"), limit(1)])
        const item = Object.values(docs as {[key:string]: {title: string, body: string, id: string}})[0];
        if (!user?.readUpdates?.includes(item.id)) setActive(item);

    } catch(error) {
         console.log(error)
    }
    
}
  

    const dismiss = () => {
        if (!user) return

        try {
            firebaseQuery.update(["users", user.id], {readUpdates: arrayUnion(active?.id)})
            //dispatch(updateUser({userId: user.id, attributes: {readUpdates: arrayUnion(active?.id)}}))
            setActive(undefined);
        }
        catch(error) {
            console.log(error)
        }
    }

  return ({...{active, dismiss, fetchUpdates}})

}  
