import fs from "node:fs";
import admin from "firebase-admin";

import { env } from "./env.js";

const getServiceAccount = () => {
  if (env.FIREBASE_SERVICE_ACCOUNT_JSON) {
    return JSON.parse(env.FIREBASE_SERVICE_ACCOUNT_JSON);
  }

  if (env.FIREBASE_SERVICE_ACCOUNT_PATH) {
    const raw = fs.readFileSync(env.FIREBASE_SERVICE_ACCOUNT_PATH, "utf-8");
    return JSON.parse(raw);
  }

  throw new Error("Missing Firebase service account configuration");
};

export const initFirebase = () => {
  if (admin.apps.length === 0) {
    const serviceAccount = getServiceAccount();
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
    });
  }

  return admin;
};
