# 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(:android)

platform :android do
  desc "Runs all the tests"
  lane :test do
    gradle(task: "test")
  end

  desc "Build bundle"
  lane :build do
    # fetch_and_increment_build_number

    gradle(
      task: "bundle", # or "assemble", if you want to build an APK
      build_type: "release",
      properties: {
        "android.injected.signing.store.file" => ENV["KEYSTORE_FILE"],
        "android.injected.signing.store.password" => ENV["KEYSTORE_PASSWORD"],
        "android.injected.signing.key.alias" => ENV["KEY_ALIAS"],
        "android.injected.signing.key.password" => ENV["KEY_PASSWORD"],
      }
    )
  end

  desc "Build apk"
  lane :assemble do
    # fetch_and_increment_build_number

    gradle(
      task: "assemble",
      build_type: "release",
      properties: {
        "android.injected.signing.store.file" => ENV["KEYSTORE_FILE"],
        "android.injected.signing.store.password" => ENV["KEYSTORE_PASSWORD"],
        "android.injected.signing.key.alias" => ENV["KEY_ALIAS"],
        "android.injected.signing.key.password" => ENV["KEY_PASSWORD"],
      }
    )
  end

  desc "Deploy a new version to Google Play"
  lane :deploy do
    version_name = get_properties_value(
      key: "VERSION",
      path: "./app/version.properties"
    )
    major, minor, patch = version_name.downcase.split('.').map(&:to_i)
    version_code = (major * 10_000) + (minor * 100) + patch

    upload_to_play_store(
      track: "alpha",
      json_key: ENV["ANDROID_JSON_KEY_FILE"],
      version_name: version_name,
      version_code: version_code,
      aab: "./app/build/outputs/bundle/release/app-release.aab"
    )
  end

  # desc "Fetches the latest version code from the Play Console and increments it by 1"
  # lane :fetch_and_increment_build_number do
  #   app_identifier = CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier)

  #   version_codes = google_play_track_version_codes(
  #     package_name: app_identifier,
  #     track: "internal",
  #     json_key: ENV["ANDROID_JSON_KEY_FILE"]
  #   )

  #   updated_version_code = version_codes[0] + 1

  #   increment_version_code(
  #     version_code: updated_version_code
  #   )
  # end
end
