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

/**
 * Local Expo Config Plugin for @uiw/react-native-alipay
 * Configures iOS URL Schemes and Android queries for Alipay SDK
 */
const withAlipay = (config, { alipayScheme = 'alipay' } = {}) => {
  // iOS: Add URL Scheme for Alipay callback
  config = withInfoPlist(config, (config) => {
    if (!config.modResults.CFBundleURLTypes) {
      config.modResults.CFBundleURLTypes = [];
    }

    // Check if alipay scheme already exists
    const existingScheme = config.modResults.CFBundleURLTypes.find(
      (urlType) => urlType.CFBundleURLSchemes && urlType.CFBundleURLSchemes.includes(alipayScheme)
    );

    if (!existingScheme) {
      config.modResults.CFBundleURLTypes.push({
        CFBundleURLName: 'alipay',
        CFBundleURLSchemes: [alipayScheme],
      });
    }

    // Add LSApplicationQueriesSchemes for Alipay
    if (!config.modResults.LSApplicationQueriesSchemes) {
      config.modResults.LSApplicationQueriesSchemes = [];
    }

    const alipaySchemes = ['alipay', 'alipays', 'alipayshare'];
    alipaySchemes.forEach((scheme) => {
      if (!config.modResults.LSApplicationQueriesSchemes.includes(scheme)) {
        config.modResults.LSApplicationQueriesSchemes.push(scheme);
      }
    });

    return config;
  });

  // Android: Add queries for Alipay package
  config = withAndroidManifest(config, (config) => {
    const manifest = config.modResults.manifest;

    if (!manifest.queries) {
      manifest.queries = [];
    }

    // Add package query for Alipay
    const alipayPackage = { package: [{ $: { 'android:name': 'com.eg.android.AlipayGphone' } }] };
    
    // Check if already exists
    const hasAlipayQuery = manifest.queries.some(
      (q) => q.package && q.package.some((p) => p.$ && p.$['android:name'] === 'com.eg.android.AlipayGphone')
    );

    if (!hasAlipayQuery) {
      manifest.queries.push(alipayPackage);
    }

    return config;
  });

  return config;
};

module.exports = withAlipay;
