// chat.js
import { getFirestore, collection, addDoc, query, orderBy, onSnapshot, serverTimestamp } from "firebase/firestore";
import { db } from "./firebase-config.js";

const sendMessage = (sender, content) => {
    addDoc(collection(db, 'messages'), {
        sender,
        content,
        timestamp: serverTimestamp()
    }).then(() => {
        console.log('Mensagem enviada!');
    }).catch((error) => {
        console.error('Erro ao enviar mensagem:', error);
    });
};

const getMessages = (callback) => {
    const q = query(collection(db, 'messages'), orderBy('timestamp'));
    onSnapshot(q, (snapshot) => {
        const messages = snapshot.docs.map(doc => doc.data());
        callback(messages);
    });
};

export { sendMessage, getMessages };
