import * as admin from 'firebase-admin';

// Initialize Firebase Admin SDK
// During build time on Vercel, env vars might not be available, so we skip initialization
const projectId = process.env.FIREBASE_PROJECT_ID;
const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;
const privateKey = process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n');

if (!admin.apps.length) {
  // Only initialize if we have credentials (skip during build)
  if (projectId && clientEmail && privateKey) {
    try {
      console.log('[Firebase Admin] Initializing...');
      console.log('[Firebase Admin] Project ID:', projectId);
      console.log('[Firebase Admin] Client Email:', clientEmail);
      console.log('[Firebase Admin] Private Key length:', privateKey?.length);

      admin.initializeApp({
        credential: admin.credential.cert({
          projectId,
          clientEmail,
          privateKey,
        }),
        storageBucket: `${projectId}.firebasestorage.app`,
      });

      console.log('[Firebase Admin] Initialized successfully!');
    } catch (error) {
      console.error('[Firebase Admin] Initialization failed:', error);
    }
  } else {
    console.log('[Firebase Admin] Skipping initialization - credentials not available (likely build time)');
  }
}

// Helper to ensure admin is initialized
function ensureInitialized() {
  if (!projectId || !clientEmail || !privateKey) {
    throw new Error('Firebase Admin credentials not configured');
  }
  
  if (!admin.apps.length) {
    // Try to initialize if not done yet
    admin.initializeApp({
      credential: admin.credential.cert({
        projectId,
        clientEmail,
        privateKey,
      }),
      storageBucket: `${projectId}.firebasestorage.app`,
    });
  }
}

// Export admin services with lazy initialization
export function getAdminAuth() {
  ensureInitialized();
  return admin.auth();
}

export function getAdminDb() {
  ensureInitialized();
  return admin.firestore();
}

export function getAdminStorage() {
  ensureInitialized();
  return admin.storage();
}

// Legacy exports for backward compatibility (will work at runtime)
export const adminAuth = admin.apps.length > 0 ? admin.auth() : ({} as any);
export const adminDb = admin.apps.length > 0 ? admin.firestore() : ({} as any);
export const adminStorage = admin.apps.length > 0 ? admin.storage() : ({} as any);

export default admin;

