import { ConfigContext, ExpoConfig } from "expo/config";
import { withAndroidManifest } from "expo/config-plugins";
import { existsSync } from "fs";

const FACEBOOK_APP_ID = process.env.EXPO_PUBLIC_FACEBOOK_APP_ID ?? "";
const FACEBOOK_CLIENT_TOKEN = process.env.EXPO_PUBLIC_FACEBOOK_CLIENT_TOKEN ?? "";

const GOOGLE_IOS_CLIENT_ID = process.env.EXPO_PUBLIC_GOOGLE_IOS_CLIENT_ID ?? "";
const GOOGLE_IOS_URL_SCHEME = process.env.EXPO_PUBLIC_GOOGLE_IOS_URL_SCHEME ?? "";

/**
 * Custom plugin to remove AD_ID permission from AndroidManifest.xml
 */
const withRemoveAdIdPermission = (config: any) => {
  return withAndroidManifest(config, (config) => {
    const manifest = config.modResults.manifest;
    if (!manifest["uses-permission"]) {
      manifest["uses-permission"] = [];
    }

    manifest["uses-permission"] = manifest["uses-permission"].filter(
      (perm: any) => perm.$["android:name"] !== "com.google.android.gms.permission.AD_ID"
    );

    manifest["uses-permission"].push({
      $: {
        "android:name": "com.google.android.gms.permission.AD_ID",
        "tools:node": "remove",
      },
    });
    return config;
  });
};

export default ({ config }: ConfigContext): ExpoConfig => {
  const plugins: any[] = [
    "expo-router",
    [
      "@stripe/stripe-react-native",
      {
        merchantIdentifier: "",
        enableGooglePay: true,
      },
    ],
    [
      "expo-image-picker",
      {
        photosPermission: "The app accesses your photos to let you share them with your friends.",
      },
    ],
    [
      "expo-document-picker",
      {
        iCloudContainerEnvironment: "Production",
      },
    ],
    [
      "expo-splash-screen",
      {
        image: "./assets/images/splash-icon.png",
        imageWidth: 200,
        resizeMode: "contain",
        backgroundColor: "#ffffff",
        dark: {
          backgroundColor: "#000000",
        },
      },
    ],
    [
      "expo-build-properties",
      {
        ios: {
          useFrameworks: "static",
          forceStaticLinking: ["RNFBApp", "RNFBMessaging"],
          modularHeaders: true,
        },
      },
    ],
    withRemoveAdIdPermission,
  ];

  const hasAndroidFirebase = existsSync("./google-services.json");
  const hasIosFirebase = existsSync("./GoogleService-Info.plist");
  if (hasAndroidFirebase && hasIosFirebase) {
    plugins.push("@react-native-firebase/app", "@react-native-firebase/messaging");
  }

  if (FACEBOOK_APP_ID) {
    plugins.push([
      "react-native-fbsdk-next",
      {
        appID: FACEBOOK_APP_ID,
        clientToken: FACEBOOK_CLIENT_TOKEN,
        displayName: "Investra",
        scheme: `fb${FACEBOOK_APP_ID}`,
        advertiserIDCollectionEnabled: false,
        autoLogAppEventsEnabled: false,
      },
    ]);
  }

  if (GOOGLE_IOS_CLIENT_ID && GOOGLE_IOS_URL_SCHEME) {
    plugins.push([
      "@react-native-google-signin/google-signin",
      {
        iosUrlScheme: GOOGLE_IOS_URL_SCHEME,
      },
    ]);
  }

  return {
    ...config,
    name: "Investra",
    slug: "investra",
    version: "1.0.0",
    orientation: "portrait",
    icon: "./assets/images/icon.png",
    scheme: "investra",
    userInterfaceStyle: "automatic",
    newArchEnabled: true,
    android: {
      ...(existsSync("./google-services.json") ? { googleServicesFile: "./google-services.json" } : {}),
      adaptiveIcon: {
        backgroundColor: "#E6F4FE",
        foregroundImage: "./assets/images/splash-icon.png",
      },
      edgeToEdgeEnabled: true,
      predictiveBackGestureEnabled: false,
      package: "com.softivus.investraapp",
      permissions: ["android.permission.RECORD_AUDIO"],
    },
    ios: {
      supportsTablet: true,
      bundleIdentifier: "com.softivus.investraapp",
      ...(existsSync("./GoogleService-Info.plist") ? { googleServicesFile: "./GoogleService-Info.plist" } : {}),
      infoPlist: {
        ITSAppUsesNonExemptEncryption: false,
      },
    },
    web: {
      output: "static",
      favicon: "./assets/images/favicon.png",
      bundler: "metro",
    },
    plugins,
    experiments: {
      typedRoutes: true,
      reactCompiler: true,
    },
    extra: {
      router: {},
    },

  };
};
