# 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 pubspec version (X.Y.Z, no -rc suffix) to the Dart layer as SENTRY_RELEASE.
    # Read from pubspec.yaml (same source as CI release.yaml) to guarantee consistency.
    #
    # DART_DEFINES must be a comma-separated list of base64-encoded "KEY=VALUE" entries
    # (matches Flutter's encodeDartDefines in build_info.dart). Flutter 3.38.9 has a bug
    # where assemble.dart:282 crashes if the base64 string has no '=' padding, which
    # happens when "SENTRY_RELEASE=X.Y.Z" length is divisible by 3. We append a benign
    # padding define ("_FB_PAD=") whose base64 always ends in '==' so the joined value
    # is guaranteed to contain '=', avoiding the Flutter bug.
    require 'base64'
    pubspec = File.read(File.expand_path("../../pubspec.yaml", __dir__))
    sentry_release = pubspec.match(/^version:\s+(\S+)/)[1].split("+").first
    sentry_define = Base64.strict_encode64("SENTRY_RELEASE=#{sentry_release}")
    padding_define = Base64.strict_encode64("_FB_PAD=") # always encodes to "X0ZCX1BBRD0="
    dart_defines_value = "#{sentry_define},#{padding_define}"

    # Detect Flutter DART_DEFINES bug condition. Warn when the bare sentry_define
    # has no '=' padding (would crash assemble.dart:282 without our workaround),
    # then hard-fail if the final joined value somehow still lacks '=' so we never
    # ship a build that would die in xcode_backend.dart.
    if !sentry_define.include?('=')
      UI.important("[DART_DEFINES] sentry_define '#{sentry_define}' has no '=' padding " \
                   "(SENTRY_RELEASE=#{sentry_release} length divisible by 3). " \
                   "Padding workaround active.")
    end
    if !dart_defines_value.include?('=')
      UI.user_error!("[DART_DEFINES] joined value '#{dart_defines_value}' has no '=' — " \
                     "Flutter assemble would crash with 'Improperly formatted define flag'. " \
                     "Check ios/fastlane/Fastfile padding logic.")
    end
    UI.message("[DART_DEFINES] final value: #{dart_defines_value}")

    build_app(
      scheme: "Runner",
      configuration: "Release",
      workspace: "Runner.xcworkspace",
      export_method: "app-store",
      xcargs: "DART_DEFINES=#{dart_defines_value}",
    )
    upload_to_testflight(
      skip_waiting_for_build_processing: true,
      ipa: "Runner.ipa"
    )
  end
end
