// src/services/firestore.js (No changes needed, assuming it handles nested Date objects) import { db, auth } from './firebase'; import { collection, addDoc, query, where, getDocs, orderBy, serverTimestamp } from "firebase/firestore"; // Save a new chat session to Firestore export const saveChatHistory = async (chatHistory) => { if (!auth.currentUser) { console.warn("Attempted to save chat history without a logged-in user."); return; // Ensure user is logged in } try { const userId = auth.currentUser.uid; await addDoc(collection(db, "chats"), { userId: userId, history: chatHistory, // This array now contains { role, message, timestamp } createdAt: serverTimestamp(), title: chatHistory[0]?.message || 'New Chat' }); console.log("Chat history saved successfully."); } catch (error) { console.error("Error saving chat history: ", error); } }; // Get all chat sessions for the current user export const getChatHistory = async () => { if (!auth.currentUser) return []; try { const userId = auth.currentUser.uid; const q = query(collection(db, "chats"), where("userId", "==", userId), orderBy("createdAt", "desc")); const querySnapshot = await getDocs(q); const chats = []; querySnapshot.forEach((doc) => { chats.push({ id: doc.id, ...doc.data() }); }); return chats; } catch (error) { console.error("Error fetching chat history: ", error); return []; } };