import { ConfigPlugin, withAndroidManifest } from '@expo/config-plugins';
import { ScanbotConfigPlugin } from './pluginTypes';

export const withAndroidFeature: ConfigPlugin<Pick<ScanbotConfigPlugin, 'androidCameraFeature'>> = (
  config,
  { androidCameraFeature }
) => {
  if (androidCameraFeature) {
    config = withAndroidManifest(config, (manifestProps) => {
      const { manifest } = manifestProps.modResults;
      const featureKey = 'uses-feature';

      if (!Array.isArray(manifest[featureKey])) {
        manifest[featureKey] = [];
      }

      if (
        !manifest[featureKey].find((item) => item.$['android:name'] === 'android.hardware.camera')
      ) {
        manifest[featureKey].push({
          $: {
            'android:name': 'android.hardware.camera',
            'android:required': 'true',
          },
        });
      }

      return manifestProps;
    });
  }

  return config;
};
