import admin from 'firebase-admin'; import { FIREBASE_PROJECT_ID } from '../config.js'; // Service account JSON (raw or base64) in FIREBASE_SERVICE_ACCOUNT lets the generator write usage counts to Firestore. // Without it the Admin SDK can still verify ID tokens, but Firestore writes fail outside Google Cloud. function loadServiceAccount() { const raw = process.env.FIREBASE_SERVICE_ACCOUNT; if (!raw) return null; const json = raw.trim().startsWith('{') ? raw : Buffer.from(raw, 'base64').toString('utf8'); return JSON.parse(json); } if (!admin.apps.length) { try { const serviceAccount = loadServiceAccount(); admin.initializeApp({ projectId: FIREBASE_PROJECT_ID, ...(serviceAccount && { credential: admin.credential.cert(serviceAccount) }) }); console.log(`[Firebase] Initialized generator for ${FIREBASE_PROJECT_ID} (${serviceAccount ? 'service account' : 'no service account: usage counting will fail'})`); } catch (err) { console.error('[Firebase] Init notice:', err.message); } } export { admin };