/**
 * Expo Config Plugin: manifest-permission-cleaner
 * 移除合并清单中的敏感权限，例如 ACCESS_BACKGROUND_LOCATION 与 QUERY_ALL_PACKAGES。
 */

const { withAndroidManifest } = require("@expo/config-plugins");

function ensureToolsNamespace(manifest) {
  if (!manifest.manifest) return;
  manifest.manifest.$ = manifest.manifest.$ || {};
  manifest.manifest.$["xmlns:tools"] = manifest.manifest.$["xmlns:tools"] || "http://schemas.android.com/tools";
}

function removePermissions(manifest, namesToRemove) {
  if (!manifest.manifest) return;

  const set = new Set(namesToRemove);

  const usesPermission = manifest.manifest["uses-permission"] || [];
  const usesPermissionSdk23 = manifest.manifest["uses-permission-sdk-23"] || [];

  // 先清理当前顶层清单里已有的权限条目
  manifest.manifest["uses-permission"] = usesPermission.filter((p) => {
    const name = p?.$?.["android:name"];
    return !set.has(name);
  });
  manifest.manifest["uses-permission-sdk-23"] = usesPermissionSdk23.filter((p) => {
    const name = p?.$?.["android:name"];
    return !set.has(name);
  });

  // 加入移除占位（tools:node="remove"），用于在清单合并时删除来自库 AAR 的同名权限
  for (const name of set) {
    manifest.manifest["uses-permission"] = manifest.manifest["uses-permission"] || [];
    manifest.manifest["uses-permission"].push({
      $: { "android:name": name, "tools:node": "remove" },
    });
  }
}

module.exports = function withManifestPermissionCleaner(config, options = {}) {
  const defaultPermissions = [
    "android.permission.ACCESS_BACKGROUND_LOCATION",
    "android.permission.QUERY_ALL_PACKAGES",
  ];
  const removeList = Array.isArray(options.removePermissions) && options.removePermissions.length
    ? options.removePermissions
    : defaultPermissions;

  return withAndroidManifest(config, (cfg) => {
    const manifest = cfg.modResults;

    ensureToolsNamespace(manifest);
    removePermissions(manifest, removeList);

    return cfg;
  });
};