default_platform(:ios)

platform :ios do

  desc "Load the App Store Connect API token"
  lane :load_asc_api_token do
    app_store_connect_api_key(
      key_id: ENV["IOS_ASC_KEY_ID"],
      issuer_id: ENV["IOS_ASC_ISSUER_ID"],
      key_content: ENV["IOS_ASC_KEY"],
      is_key_content_base64: true,
      in_house: false
    )
  end


  desc "Deploy a new version to closed testing (testflight)"
  lane :deploy_testing do
    build_name = ENV["BUILD_NAME"]
    build_number = ENV["BUILD_NUMBER"]
    
    load_asc_api_token
    api_key = lane_context[SharedValues::APP_STORE_CONNECT_API_KEY]

    sync_code_signing(
      api_key: api_key,
      type: "appstore",
      readonly: true,
    )


    sh(
      "flutter",
      "build",
      "ipa",
      "--debug",
      "--build-name=#{build_name}",
      "--build-number=#{build_number}",
    )

    # sign the app (whithout rebuilding it)
    build_app(
      skip_build_archive: true,
      archive_path: "../build/ios/archive/Runner.xcarchive"
    )

    upload_to_testflight(
      skip_waiting_for_build_processing: true,
    )
  end


  desc "Deploy a new version as a full release"
  lane :deploy_release do
    build_name = ENV["BUILD_NAME"]
    build_number = ENV["BUILD_NUMBER"]
    
    load_asc_api_token
    api_key = lane_context[SharedValues::APP_STORE_CONNECT_API_KEY]

    sync_code_signing(
      api_key: api_key,
      type: "appstore",
      readonly: true,
    )

    # replace secrets by real values, the stupid way
    sh(
      "sed",
      "-i",
      "",
      "s/IOS_GOOGLE_MAPS_API_KEY/#{ENV["IOS_GOOGLE_MAPS_API_KEY"]}/g",
      "../Runner/AppDelegate.swift"

    )

    sh(
      "flutter",
      "build",
      "ipa",
      "--release",
      "--build-name=#{build_name}",
      "--build-number=#{build_number}",
    )

    # sign the app (whithout rebuilding it)
    build_app(
      skip_build_archive: true,
      archive_path: "../build/ios/archive/Runner.xcarchive"
    )
  
    upload_to_app_store(
      skip_screenshots: true,
      skip_metadata: true,
      precheck_include_in_app_purchases: false,
      
      submit_for_review: true,
      automatic_release: true,
      # automatically release the app after review
    )
  end
end