const admin = require('firebase-admin');
const dotenv = require('dotenv');

dotenv.config();

const initFirebaseAdmin = () => {
    if (admin.apps.length) {
        return admin;
    }

    const credentialPath = process.env.GOOGLE_APPLICATION_CREDENTIALS;
    if (!credentialPath) {
        throw new Error(
            'GOOGLE_APPLICATION_CREDENTIALS no está definida. Configúrala antes de inicializar Firebase Admin.'
        );
    }

    const options = {
        credential: admin.credential.applicationDefault()
    };

    if (process.env.FIREBASE_DATABASE_URL) {
        options.databaseURL = process.env.FIREBASE_DATABASE_URL;
    }

    admin.initializeApp(options);
    return admin;
};

module.exports = {
    admin,
    initFirebaseAdmin
};
