/* Injects a release signing config into the prebuilt android project.
   Keystore: $HEALTH_KEYSTORE or ~/.android-keys/health-app-release.jks
   Password: $KEYSTORE_PASSWORD or ~/.android-keys/health-app-release.password
   Falls back to the debug keystore when neither exists. */
const { withAppBuildGradle } = require('expo/config-plugins');

const SIGNING = `        release {
            // keystore lives outside the repo; password from env or ~/.android-keys
            def ksPath = System.getenv("HEALTH_KEYSTORE") ?: "\${System.properties['user.home']}/.android-keys/health-app-release.jks"
            def passFile = new File("\${System.properties['user.home']}/.android-keys/health-app-release.password")
            def ksPass = System.getenv("KEYSTORE_PASSWORD") ?: (passFile.exists() ? passFile.text.trim() : null)
            if (new File(ksPath).exists() && ksPass != null) {
                storeFile file(ksPath)
                storePassword ksPass
                keyAlias System.getenv("KEY_ALIAS") ?: "health"
                keyPassword ksPass
            }
        }
    }`;

module.exports = function withReleaseSigning(config) {
  return withAppBuildGradle(config, (cfg) => {
    let g = cfg.modResults.contents;
    if (!g.includes('def ksPath')) {
      g = g.replace(
        /(signingConfigs \{[\s\S]*?keyPassword 'android'\n {8}\}\n)( {4}\})/,
        `$1${SIGNING}`,
      );
      g = g.replace(
        /\/\/ Caution![^\n]*\n\s*\/\/ see https:\/\/reactnative\.dev[^\n]*\n\s*signingConfig signingConfigs\.debug/,
        'signingConfig signingConfigs.release.storeFile ? signingConfigs.release : signingConfigs.debug',
      );
      cfg.modResults.contents = g;
    }
    return cfg;
  });
};
