const { withAndroidManifest, AndroidConfig, createRunOncePlugin } = require('@expo/config-plugins');

const AK = 'w5SWSj0Z69I9gyy3w3I4On2g3tvfYrJs';

function withBaiduAKInject(config) {
  config = withAndroidManifest(config, (c) => {
    try {
      const app = AndroidConfig.Manifest.getMainApplicationOrThrow(c.modResults);
      const metas = Array.isArray(app['meta-data']) ? app['meta-data'] : [];
      const idx = metas.findIndex((m) => m.$ && m.$['android:name'] === 'com.baidu.lbsapi.API_KEY');
      if (idx >= 0) {
        metas[idx].$['android:value'] = AK;
      } else {
        metas.push({ $: { 'android:name': 'com.baidu.lbsapi.API_KEY', 'android:value': AK } });
      }
      app['meta-data'] = metas;
    } catch (e) {
      if (process.env.NODE_ENV !== 'production') {
        console.warn('[baidu-location-react-native] AK inject failed:', e && e.message ? e.message : e);
      }
    }
    return c;
  });
  return config;
}

module.exports = createRunOncePlugin(withBaiduAKInject, 'baidu-location-react-native-ak-injector', '1.0.0');