File size: 1,474 Bytes
9f7a5a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 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 [];
  }
};