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

const BLOCKED_PERMISSIONS = [
  'android.permission.READ_MEDIA_IMAGES',
  'android.permission.READ_MEDIA_VIDEO',
];

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

    // Pastikan xmlns:tools ada di manifest root
    if (!manifest.$['xmlns:tools']) {
      manifest.$['xmlns:tools'] = 'http://schemas.android.com/tools';
    }

    // Hapus entry yang ada (apapun atributnya)
    const existing = manifest['uses-permission'] ?? [];
    manifest['uses-permission'] = existing.filter(
      (perm) => !BLOCKED_PERMISSIONS.includes(perm.$?.['android:name'])
    );

    // Tambahkan entry dengan tools:node="remove" agar Gradle merger
    // membuang permission ini dari SEMUA sumber (termasuk library manifests)
    for (const permission of BLOCKED_PERMISSIONS) {
      manifest['uses-permission'].push({
        $: {
          'android:name': permission,
          'tools:node': 'remove',
        },
      });
    }

    return config;
  });

module.exports = withRemoveMediaPermissions;
