import admin from 'firebase-admin'
import { readFileSync } from 'fs'
import { resolve, dirname } from 'path'
import { fileURLToPath } from 'url'

const __dirname = dirname(fileURLToPath(import.meta.url))

let initialized = false

/**
 * Initializes Firebase Admin SDK. Phase 3.4+ only uses this for FCM (messaging);
 * authentication is handled by our own token service.
 */
export const initFirebase = () => {
  if (initialized) return

  const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH
    || resolve(__dirname, '../../firebase-service-account.json')

  const serviceAccount = JSON.parse(readFileSync(serviceAccountPath, 'utf8'))
  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
  })
  initialized = true
}
