File size: 4,594 Bytes
e2a1a46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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;
    }
}