# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
update_fastlane

opt_out_usage
default_platform(:ios)
setup_ci if ENV['CI']

platform :ios do
  desc "Build development version"
  lane :dev do
    sync_code_signing(
      type: "development",
      git_private_key: ENV["APPLE_CERTIFICATES_SSH_KEY"]
    )
    build_app(
      scheme: "Runner",
      configuration: "Debug",
      workspace: "Runner.xcworkspace",
      export_method: "development",
    )
  end

  desc "Build and deploy release version"
  lane :release do
    # App Store Connect API setup
    app_store_connect_api_key(
      key_id: ENV["APPLE_KEY_ID"],
      issuer_id: ENV["APPLE_ISSUER_ID"],
      key_content: ENV["APPLE_KEY_CONTENT"]
    )
    sync_code_signing(
      type: "appstore",
      git_private_key: ENV["APPLE_CERTIFICATES_SSH_KEY"]
    )
    increment_build_number(
      build_number: latest_testflight_build_number + 1
    )
    increment_version_number(
      version_number: last_git_tag.gsub("v", "").split("-").first
    )
    # Pass the full release tag (e.g. "0.28.3-rc09") to the Dart layer so the
    # app reports the same string to Sentry as CI uses when uploading dSYMs.
    # This is separate from increment_version_number (which stays numeric for
    # App Store compatibility). Each dart-define must be base64-encoded.
    require 'base64'
    sentry_release = last_git_tag.gsub("v", "")
    sentry_release_define = Base64.strict_encode64("SENTRY_RELEASE=#{sentry_release}")
    build_app(
      scheme: "Runner",
      configuration: "Release",
      workspace: "Runner.xcworkspace",
      export_method: "app-store",
      xcargs: "DART_DEFINES=#{sentry_release_define}",
    )
    upload_to_testflight(
      skip_waiting_for_build_processing: true,
      ipa: "Runner.ipa"
    )
  end
end
