// src/firebase.ts
import admin from "firebase-admin";
import * as fs from "fs";
import * as path from "path";
import * as dotenv from "dotenv";

dotenv.config({ path: path.resolve(process.cwd(), ".env") });

const USE_EMULATOR = process.env.USE_EMULATOR === "true";

/* -------------------------------------------------------------
   1. EMULATOR MODE – 100% LOCAL, ZERO CLOUD CALLS
   BUT: Still verify production Firebase Auth tokens
   ------------------------------------------------------------- */
if (USE_EMULATOR) {
  // Tell Admin SDK to talk to the local emulators for Firestore and Storage
  process.env.FIRESTORE_EMULATOR_HOST = "localhost:8080";
  // NOTE: Do NOT set FIREBASE_AUTH_EMULATOR_HOST - we want to verify production tokens
  // process.env.FIREBASE_AUTH_EMULATOR_HOST = "localhost:9099"; // ❌ Commented out
  process.env.FIREBASE_STORAGE_EMULATOR_HOST = "localhost:9199";

  // Load service account to verify production Firebase tokens
  const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;
  let serviceAccount: any;

  if (serviceAccountPath) {
    const fullPath = path.resolve(process.cwd(), serviceAccountPath);
    if (fs.existsSync(fullPath)) {
      serviceAccount = JSON.parse(fs.readFileSync(fullPath, "utf8"));
    }
  } else if (process.env.FIREBASE_SERVICE_ACCOUNT) {
    serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT);
  }

  if (!admin.apps.length) {
    if (serviceAccount) {
      // Initialize with service account to verify production tokens
      admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
        projectId: serviceAccount.project_id || "electronic-log-book-2d67f",
        storageBucket: `${serviceAccount.project_id}.appspot.com`,
      });
      console.log("Firebase EMULATOR mode (Firestore emulator, but verifying production Auth tokens)");
    } else {
      // Fallback: no service account, use minimal config
      admin.initializeApp({
        projectId: "electronic-log-book-2d67f",
        storageBucket: "elb-backend.appspot.com",
      });
      console.log("Firebase EMULATOR mode (WARNING: No service account - Auth verification may fail)");
    }
  }
}

/* -------------------------------------------------------------
   2. PRODUCTION MODE – LIVE FIREBASE (uses your JSON key)
   ------------------------------------------------------------- */
else {
  const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;
  let serviceAccount: any;

  if (serviceAccountPath) {
    const fullPath = path.resolve(process.cwd(), serviceAccountPath);
    serviceAccount = JSON.parse(fs.readFileSync(fullPath, "utf8"));
  } else if (process.env.FIREBASE_SERVICE_ACCOUNT) {
    serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT);
  } else {
    throw new Error(
      "Firebase service account not found. Set FIREBASE_SERVICE_ACCOUNT_PATH or FIREBASE_SERVICE_ACCOUNT."
    );
  }

  if (!admin.apps.length) {
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      storageBucket: `${serviceAccount.project_id}.appspot.com`,
    });
  }

  console.log("Firebase PRODUCTION mode (live project)");
}

/* -------------------------------------------------------------
   3. EXPORT SDKs – same in both modes
   ------------------------------------------------------------- */
export const db = admin.firestore();
export const auth = admin.auth();

// APPLY EMULATOR SETTINGS (THIS WAS MISSING!)
if (USE_EMULATOR) {
  db.settings({
    host: process.env.EMULATOR_FIRESTORE_HOST || "localhost:8080",
    ssl: false,
  });

  // Optional: Log for confirmation
  console.log("Firestore Emulator connected: localhost:8080");
}

// In emulator: use dummy bucket name
// In production: bucket() auto-uses the default bucket from init
export const bucket = admin
  .storage()
  .bucket(USE_EMULATOR ? "elb-backend.appspot.com" : undefined);

export { admin };