// Firebase 클라이언트 초기화 (env에서 config 로드). 실제 키는 .env.local 에.
// 사용처: lib/data.ts(Firestore 읽기), Arena.tsx 제출(콜러블 함수 호출).
import { initializeApp, getApps, type FirebaseApp } from "firebase/app";
import { getFirestore, type Firestore } from "firebase/firestore";
import { getFunctions, type Functions } from "firebase/functions";

const config = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};

let app: FirebaseApp | null = null;
export function getFirebase(): { db: Firestore; fns: Functions } {
  if (!config.projectId) {
    throw new Error("Firebase env 미설정 — .env.local 에 NEXT_PUBLIC_FIREBASE_* 채우기");
  }
  app = getApps()[0] ?? initializeApp(config);
  const region = process.env.NEXT_PUBLIC_FUNCTIONS_REGION || "asia-northeast3";
  return { db: getFirestore(app), fns: getFunctions(app, region) };
}
