import * as admin from 'firebase-admin'
import * as fs from 'fs'

let initialized = false

export function initFirebase(): void {
  if (initialized) return

  const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH
  const serviceAccountJson = process.env.FIREBASE_SERVICE_ACCOUNT_JSON

  let credential: admin.credential.Credential

  if (serviceAccountJson) {
    const parsed = JSON.parse(serviceAccountJson)
    credential = admin.credential.cert(parsed)
  } else if (serviceAccountPath && fs.existsSync(serviceAccountPath)) {
    credential = admin.credential.cert(serviceAccountPath)
  } else {
    // Falls back to Application Default Credentials (works on GCP/Cloud Run)
    credential = admin.credential.applicationDefault()
  }

  admin.initializeApp({
    credential,
    projectId: process.env.FIREBASE_PROJECT_ID,
  })

  initialized = true
}

export const db = (): FirebaseFirestore.Firestore => admin.firestore()
export const messaging = (): admin.messaging.Messaging => admin.messaging()
