const admin = require('firebase-admin'); const path = require('path'); const fs = require('fs'); let db; let firebaseReady = false; let firebaseInitError = null; function normalizePrivateKey(value) { if (!value) return value; return value.includes('\\n') ? value.replace(/\\n/g, '\n') : value; } function parseJson(value, label) { try { return JSON.parse(value); } catch (error) { throw new Error(`${label} is not valid JSON: ${error.message}`); } } function loadServiceAccount() { const jsonEnv = process.env.FIREBASE_SERVICE_ACCOUNT_JSON; if (jsonEnv && jsonEnv.trim()) { return parseJson(jsonEnv, 'FIREBASE_SERVICE_ACCOUNT_JSON'); } const b64Env = process.env.FIREBASE_SERVICE_ACCOUNT_JSON_B64 || process.env.FIREBASE_SERVICE_ACCOUNT_BASE64; if (b64Env && b64Env.trim()) { const decoded = Buffer.from(b64Env, 'base64').toString('utf8'); return parseJson(decoded, 'FIREBASE_SERVICE_ACCOUNT_JSON_B64'); } const projectId = process.env.FIREBASE_PROJECT_ID; const clientEmail = process.env.FIREBASE_CLIENT_EMAIL; const privateKey = normalizePrivateKey(process.env.FIREBASE_PRIVATE_KEY); if (projectId && clientEmail && privateKey) { return { project_id: projectId, client_email: clientEmail, private_key: privateKey, }; } let serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH; if (!serviceAccountPath) { 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; } } } if (serviceAccountPath && fs.existsSync(serviceAccountPath)) { return require(serviceAccountPath); } throw new Error( [ 'Firebase service account missing.', 'Set one of these in Hugging Face Secrets:', '- FIREBASE_SERVICE_ACCOUNT_JSON', '- FIREBASE_SERVICE_ACCOUNT_JSON_B64', '- FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY', ].join(' '), ); } function createNoopSnapshot(value = null) { return { exists: () => Boolean(value), val: () => value, forEach: () => false, }; } function createNoopQuery() { const query = { once: async () => createNoopSnapshot(null), get: async () => ({ empty: true, docs: [] }), set: async () => undefined, update: async () => undefined, remove: async () => undefined, on: () => undefined, off: () => undefined, orderByChild: () => query, equalTo: () => query, limitToLast: () => query, limit: () => query, where: () => query, doc: () => query, collection: () => query, push: () => ({ key: `noop-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`, set: async () => undefined, update: async () => undefined, }), }; return query; } function createNoopDb() { const root = createNoopQuery(); return { ref: () => root, collection: () => root, doc: () => root, }; } function createNoopAuth() { const unavailable = (method) => { const error = new Error(`Firebase Admin is not configured. Cannot call ${method}.`); error.code = 'auth/internal-error'; throw error; }; return { getUserByEmail: async () => unavailable('getUserByEmail'), getUser: async () => unavailable('getUser'), createUser: async () => unavailable('createUser'), createCustomToken: async () => unavailable('createCustomToken'), verifyIdToken: async () => unavailable('verifyIdToken'), }; } function createNoopMessaging() { return { send: async () => { const error = new Error('Firebase messaging is not configured.'); error.code = 'messaging/unavailable'; throw error; }, sendEachForMulticast: async () => { const error = new Error('Firebase messaging is not configured.'); error.code = 'messaging/unavailable'; throw error; }, }; } function initializeFirebase() { if (admin.apps.length) { firebaseReady = true; return true; } const serviceAccount = loadServiceAccount(); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: process.env.FIREBASE_DATABASE_URL || 'https://serviceconnect-dea35-default-rtdb.firebaseio.com/', }); firebaseReady = true; return true; } try { initializeFirebase(); console.log('Firebase Admin initialized successfully'); } catch (error) { firebaseInitError = error; firebaseReady = false; console.error('Firebase initialization failed:', error.message); } if (firebaseReady) { db = admin.database(); } else { db = createNoopDb(); } const auth = firebaseReady ? admin.auth() : createNoopAuth(); const messaging = firebaseReady ? admin.messaging() : createNoopMessaging(); async function dbGet(pathName) { try { const snap = await db.ref(pathName).once('value'); return snap.exists() ? snap.val() : null; } catch (error) { console.error(`dbGet error at ${pathName}:`, error.message); return null; } } async function dbSet(pathName, data) { try { await db.ref(pathName).set({ ...data, _updatedAt: Date.now() }); return true; } catch (error) { console.error(`dbSet error at ${pathName}:`, error.message); return false; } } async function dbUpdate(pathName, data) { try { await db.ref(pathName).update({ ...data, _updatedAt: Date.now() }); return true; } catch (error) { console.error(`dbUpdate error at ${pathName}:`, error.message); return false; } } async function dbPush(pathName, data) { try { const ref = db.ref(pathName).push(); await ref.set({ ...data, id: ref.key, _createdAt: Date.now() }); return ref.key; } catch (error) { console.error(`dbPush error at ${pathName}:`, error.message); return null; } } async function dbDelete(pathName) { try { await db.ref(pathName).remove(); return true; } catch (error) { console.error(`dbDelete error at ${pathName}:`, error.message); return false; } } async function dbQuery(pathName, orderBy, equalTo, limitToLast = null) { try { let ref = db.ref(pathName).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 ${pathName}:`, error.message); return []; } } async function dbGetAll(pathName) { try { const snap = await db.ref(pathName).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 ${pathName}:`, error.message); return []; } } function dbListen(pathName, callback) { const ref = db.ref(pathName); ref.on('value', (snapshot) => { callback(snapshot.exists() ? snapshot.val() : null); }); return () => ref.off(); } module.exports = { admin, db, auth, messaging, firebaseReady, firebaseInitError, dbGet, dbSet, dbUpdate, dbPush, dbDelete, dbQuery, dbGetAll, dbListen, };