default_platform(:ios)

platform :ios do
  desc 'Upload App Store screenshots using fastlane/Deliverfile'
  lane :upload_screenshots do
    missing_api_key_env = %w[APPLE_KEY_ID APPLE_ISSUER_ID APPLE_KEY_CONTENT].select { |key| ENV[key].to_s.strip.empty? }
    unless missing_api_key_env.empty?
      UI.user_error!("Missing App Store Connect API key environment variables: #{missing_api_key_env.join(', ')}")
    end

    api_key = app_store_connect_api_key(
      key_id: ENV.fetch('APPLE_KEY_ID'),
      issuer_id: ENV.fetch('APPLE_ISSUER_ID'),
      key_content: ENV.fetch('APPLE_KEY_CONTENT'),
      is_key_content_base64: true
    )

    deliver(api_key: api_key)
  end

  desc 'Submit iOS app for App Store review'
  lane :submit_review do
    deliver(
      submit_for_review: true,
      automatic_release: true,
      force: true,
      skip_metadata: false,
      skip_screenshots: false,
      skip_binary_upload: true
    )
  end
end

platform :android do
  desc 'Upload Google Play screenshots'
  lane :upload_screenshots do
    metadata_path = File.expand_path('metadata/android', __dir__)
    screenshot_paths = %w[
      phoneScreenshots
      sevenInchScreenshots
      tenInchScreenshots
    ].map { |directory| File.join(metadata_path, 'en-US/images', directory) }
    missing_screenshot_paths = screenshot_paths.select do |screenshots_path|
      %w[png jpg jpeg].flat_map { |extension| Dir[File.join(screenshots_path, "*.#{extension}")] }.empty?
    end
    unless missing_screenshot_paths.empty?
      UI.user_error!("No Android screenshots found in: #{missing_screenshot_paths.join(', ')}")
    end

    json_key = ENV['ANDROID_JSON_KEY_FILE'].to_s.strip
    UI.user_error!('ANDROID_JSON_KEY_FILE must point to your Google Play service account JSON file') if json_key.empty?

    json_key_path = File.expand_path(json_key)
    unless File.file?(json_key_path) && File.readable?(json_key_path)
      UI.user_error!("ANDROID_JSON_KEY_FILE does not point to a readable file: #{json_key_path}")
    end

    upload_to_play_store(
      json_key: json_key_path,
      package_name: ENV['DEVELOPER_PACKAGE_NAME'].to_s.empty? ? 'ee.forgr.capacitor_go' : ENV.fetch('DEVELOPER_PACKAGE_NAME'),
      metadata_path: metadata_path,
      skip_upload_apk: true,
      skip_upload_aab: true,
      skip_upload_metadata: true,
      skip_upload_changelogs: true,
      skip_upload_images: true,
      skip_upload_screenshots: false,
      sync_image_upload: true
    )
  end
end
