/**
 * Expo config plugin: inject a release signingConfig into android/app/build.gradle
 * that reads credentials from environment variables (set by CI). This survives
 * `expo prebuild --clean`, so signed builds are reproducible without committing
 * the generated android/ directory.
 *
 * Env vars (see .gitea/workflows/build-apk.yml):
 *   BBP_UPLOAD_STORE_FILE, BBP_UPLOAD_STORE_PASSWORD,
 *   BBP_UPLOAD_KEY_ALIAS,  BBP_UPLOAD_KEY_PASSWORD
 *
 * If the env vars are absent (local dev), the build falls back to the debug key.
 */
const { withAppBuildGradle } = require('@expo/config-plugins');

const SIGNING_BLOCK = `
        release {
            def storeFilePath = System.getenv("BBP_UPLOAD_STORE_FILE")
            if (storeFilePath != null) {
                storeFile file(storeFilePath)
                storePassword System.getenv("BBP_UPLOAD_STORE_PASSWORD")
                keyAlias System.getenv("BBP_UPLOAD_KEY_ALIAS")
                keyPassword System.getenv("BBP_UPLOAD_KEY_PASSWORD")
            }
        }`;

module.exports = function withReleaseSigning(config) {
  return withAppBuildGradle(config, (cfg) => {
    let gradle = cfg.modResults.contents;

    // 1) Add a `release` signingConfig next to the default `debug` one.
    if (!gradle.includes('BBP_UPLOAD_STORE_FILE')) {
      gradle = gradle.replace(
        /signingConfigs \{/,
        `signingConfigs {${SIGNING_BLOCK}`,
      );
      // 2) Point the release buildType at the release key when its env is set, else
      //    debug. Anchor on `buildTypes { … release {` so we hit the release
      //    BUILD TYPE's debug line — not the `release {}` we just added inside
      //    signingConfigs {} (which would leave release builds on the debug key).
      gradle = gradle.replace(
        /(buildTypes \{[\s\S]*?release \{[\s\S]*?)signingConfig signingConfigs\.debug/,
        `$1signingConfig System.getenv("BBP_UPLOAD_STORE_FILE") != null ? signingConfigs.release : signingConfigs.debug`,
      );
    }

    cfg.modResults.contents = gradle;
    return cfg;
  });
};
