const { notarize } = require('@electron/notarize');

exports.default = async function notarizing(context) {
  const { electronPlatformName, appOutDir } = context;

  // Only notarize on macOS
  if (electronPlatformName !== 'darwin') {
    console.log('⏭️  Skipping notarization: Not a macOS build');
    return;
  }

  // Skip if credentials are not provided
  if (!process.env.APPLE_ID || !process.env.APPLE_APP_SPECIFIC_PASSWORD || !process.env.APPLE_TEAM_ID) {
    console.log('⏭️  Skipping notarization: Apple credentials not provided');
    console.log('   To enable notarization, set these environment variables:');
    console.log('   - APPLE_ID');
    console.log('   - APPLE_APP_SPECIFIC_PASSWORD');
    console.log('   - APPLE_TEAM_ID');
    return;
  }

  const appName = context.packager.appInfo.productFilename;
  const appPath = `${appOutDir}/${appName}.app`;
  const appBundleId = context.packager.appInfo.id;

  console.log('');
  console.log('🍎 Starting notarization process...');
  console.log(`   App Bundle ID: ${appBundleId}`);
  console.log(`   App Path: ${appPath}`);
  console.log(`   Apple ID: ${process.env.APPLE_ID}`);
  console.log(`   Team ID: ${process.env.APPLE_TEAM_ID}`);
  console.log('');

  try {
    await notarize({
      appBundleId: appBundleId,
      appPath: appPath,
      appleId: process.env.APPLE_ID,
      appleIdPassword: process.env.APPLE_APP_SPECIFIC_PASSWORD,
      teamId: process.env.APPLE_TEAM_ID,
    });

    console.log('');
    console.log('✅ Notarization successful!');
    console.log('');
  } catch (error) {
    console.error('');
    console.error('❌ Notarization failed:');
    console.error(error.message);
    console.error('');

    // Don't fail the build if notarization fails
    // The app will still be signed, just not notarized
    console.warn('⚠️  Continuing build without notarization...');
    console.warn('   Users may see Gatekeeper warnings when opening the app.');
  }
};
