import { db, auth } from './firebase-config.js'; import { doc, updateDoc, arrayUnion, getDoc, setDoc, serverTimestamp } from "https://www.gstatic.com/firebasejs/9.22.0/firebase-firestore.js"; export async function saveScanToHistory(scanData) { const user = auth.currentUser; if (!user) return; try { const userRef = doc(db, "users", user.uid); const scanEntry = { id: Date.now().toString(), timestamp: new Date().toISOString(), patientName: scanData.patient_name || "Unknown", doctorName: scanData.doctor_name || "Unknown", medicineCount: scanData.medicines ? scanData.medicines.length : 0, diagnosis: scanData.diagnosis || "N/A", data: scanData // Save full data for re-display }; // Use setDoc with merge: true to ensure document exists await setDoc(userRef, { scanningHistory: arrayUnion(scanEntry) }, { merge: true }); console.log("Scan saved to history"); } catch (error) { console.error("Error saving scan to history:", error); // Don't throw, just log. We don't want to break the app flow if saving fails. } } export async function getUserHistory() { const user = auth.currentUser; if (!user) throw new Error("User not authenticated"); try { const userRef = doc(db, "users", user.uid); const docSnap = await getDoc(userRef); if (docSnap.exists()) { const data = docSnap.data(); const history = data.scanningHistory || []; // 24-hour expiration logic const now = Date.now(); const twentyFourHoursAgo = now - (24 * 60 * 60 * 1000); const validHistory = history.filter(item => { const itemTime = new Date(item.timestamp).getTime(); return itemTime > twentyFourHoursAgo; }); // If we filtered out any items, update the database if (validHistory.length !== history.length) { console.log(`Cleaning up ${history.length - validHistory.length} expired items`); await updateDoc(userRef, { scanningHistory: validHistory }); } // Return history sorted by timestamp descending (newest first) return validHistory.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp) ); } else { console.log("No such document!"); return []; } } catch (error) { console.error("Error fetching history:", error); throw error; } } export async function deleteHistoryItem(itemId) { const user = auth.currentUser; if (!user) throw new Error("User not authenticated"); try { const userRef = doc(db, "users", user.uid); const docSnap = await getDoc(userRef); if (docSnap.exists()) { const data = docSnap.data(); const history = data.scanningHistory || []; const newHistory = history.filter(item => item.id !== itemId); if (newHistory.length !== history.length) { await updateDoc(userRef, { scanningHistory: newHistory }); console.log("Item deleted"); return true; } } return false; } catch (error) { console.error("Error deleting history item:", error); throw error; } } export async function getUserProfile() { const user = auth.currentUser; if (!user) throw new Error("User not authenticated"); try { const userRef = doc(db, "users", user.uid); const docSnap = await getDoc(userRef); if (docSnap.exists()) { return docSnap.data(); } else { // Self-healing: Create document if it doesn't exist console.log("User document missing, creating now..."); const newProfile = { uid: user.uid, email: user.email, createdAt: serverTimestamp(), role: "user", scanningHistory: [] }; await setDoc(userRef, newProfile); // Return the new profile (with client-side timestamp for immediate display) return { ...newProfile, createdAt: new Date() }; } } catch (error) { console.error("Error fetching profile:", error); throw error; } }