File size: 5,016 Bytes
e3fefe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
const admin = require('firebase-admin');
const path = require('path');
const fs = require('fs');

let db;

// Initialize Firebase Admin only once
if (!admin.apps.length) {
  // Try to get path from environment variable, otherwise use default
  let serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;
  
  if (!serviceAccountPath) {
    // Try multiple possible locations
    const possiblePaths = [
      path.resolve(__dirname, './serviceAccountKey.json'),
      path.resolve(__dirname, '../config/serviceAccountKey.json'),
      path.resolve(process.cwd(), './src/config/serviceAccountKey.json'),
      path.resolve(process.cwd(), './serviceAccountKey.json'),
    ];
    
    for (const possiblePath of possiblePaths) {
      if (fs.existsSync(possiblePath)) {
        serviceAccountPath = possiblePath;
        break;
      }
    }
  }

  // Final check
  if (!serviceAccountPath || !fs.existsSync(serviceAccountPath)) {
    console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.error('❌ FIREBASE SERVICE ACCOUNT KEY NOT FOUND!');
    console.error(`   Expected at: ${serviceAccountPath || 'src/config/serviceAccountKey.json'}`);
    console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    process.exit(1);
  }

  console.log(`πŸ“ Loading service account from: ${serviceAccountPath}`);
  
  // Load service account JSON
  const serviceAccount = require(serviceAccountPath);

  // Initialize Firebase Admin
  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: process.env.FIREBASE_DATABASE_URL || 'https://serviceconnect-dea35-default-rtdb.firebaseio.com/',
  });

  console.log('βœ… Firebase Admin (Realtime Database) initialized successfully');
}

// Realtime Database reference
db = admin.database();
const auth = admin.auth();
const messaging = admin.messaging();

// ─── Realtime Database Helpers ────────────────────────────────────────────────

/**
 * Get value at a path
 */
async function dbGet(path) {
  try {
    const snap = await db.ref(path).once('value');
    return snap.exists() ? snap.val() : null;
  } catch (error) {
    console.error(`❌ dbGet error at ${path}:`, error.message);
    return null;
  }
}

/**
 * Set value at a path (overwrites)
 */
async function dbSet(path, data) {
  try {
    await db.ref(path).set({ ...data, _updatedAt: Date.now() });
    return true;
  } catch (error) {
    console.error(`❌ dbSet error at ${path}:`, error.message);
    return false;
  }
}

/**
 * Update (merge) value at a path
 */
async function dbUpdate(path, data) {
  try {
    await db.ref(path).update({ ...data, _updatedAt: Date.now() });
    return true;
  } catch (error) {
    console.error(`❌ dbUpdate error at ${path}:`, error.message);
    return false;
  }
}

/**
 * Push to a list (auto-ID)
 */
async function dbPush(path, data) {
  try {
    const ref = db.ref(path).push();
    await ref.set({ ...data, id: ref.key, _createdAt: Date.now() });
    return ref.key;
  } catch (error) {
    console.error(`❌ dbPush error at ${path}:`, error.message);
    return null;
  }
}

/**
 * Delete a path
 */
async function dbDelete(path) {
  try {
    await db.ref(path).remove();
    return true;
  } catch (error) {
    console.error(`❌ dbDelete error at ${path}:`, error.message);
    return false;
  }
}

/**
 * Query children where field == value
 */
async function dbQuery(path, orderBy, equalTo, limitToLast = null) {
  try {
    let ref = db.ref(path).orderByChild(orderBy).equalTo(equalTo);
    if (limitToLast) ref = ref.limitToLast(limitToLast);
    const snap = await ref.once('value');
    if (!snap.exists()) return [];
    const results = [];
    snap.forEach(child => results.push({ _key: child.key, ...child.val() }));
    return results;
  } catch (error) {
    console.error(`❌ dbQuery error at ${path}:`, error.message);
    return [];
  }
}

/**
 * Get all children of a path
 */
async function dbGetAll(path) {
  try {
    const snap = await db.ref(path).once('value');
    if (!snap.exists()) return [];
    const results = [];
    snap.forEach(child => results.push({ _key: child.key, ...child.val() }));
    return results;
  } catch (error) {
    console.error(`❌ dbGetAll error at ${path}:`, error.message);
    return [];
  }
}

/**
 * Listen to realtime updates at a path
 */
function dbListen(path, callback) {
  const ref = db.ref(path);
  ref.on('value', (snapshot) => {
    callback(snapshot.exists() ? snapshot.val() : null);
  });
  return () => ref.off(); // Return unsubscribe function
}

module.exports = { 
  admin, 
  db, 
  auth, 
  messaging,
  dbGet, 
  dbSet, 
  dbUpdate, 
  dbPush, 
  dbDelete, 
  dbQuery, 
  dbGetAll,
  dbListen 
};