default_platform(:mac)
build_number = 1000000000 + number_of_commits()

platform :mac do
  desc "Setup the LunaSea Keychain"
  lane :prepare_keychain do
    create_keychain(
      name: ENV["MATCH_KEYCHAIN_NAME"],
      password: ENV["MATCH_KEYCHAIN_PASSWORD"],
      default_keychain: is_ci,
      unlock: true,
      timeout: 3600,
      lock_when_sleeps: false
    )

    # Development
    match(
      type: "development",
      readonly: is_ci,
      keychain_name: ENV["MATCH_KEYCHAIN_NAME"],
      keychain_password: ENV["MATCH_KEYCHAIN_PASSWORD"],
    )

    # App Store Connect
    match(
      type: "appstore",
      additional_cert_types: "mac_installer_distribution",
      readonly: is_ci,
      keychain_name: ENV["MATCH_KEYCHAIN_NAME"],
      keychain_password: ENV["MATCH_KEYCHAIN_PASSWORD"],
    )
  end

  desc "Destroy the LunaSea Keychain"
  lane :destroy_keychain do
    delete_keychain(name: ENV["MATCH_KEYCHAIN_NAME"])
  end

  desc "Build App Package"
  lane :build do
    prepare_keychain
    sh("flutter", "build", "macos", "--release", "--build-number=#{build_number}")
    build_mac_app(scheme: "Runner", workspace: "Runner.xcworkspace", export_method: "app-store")
    destroy_keychain
  end

  desc "Deploy to App Store Connect"
  lane :deploy do |options|
    api_key = app_store_connect_api_key(
      key_id: ENV["APPLE_STORE_CONNECT_KEY_ID"],
      issuer_id: ENV["APPLE_STORE_CONNECT_ISSUER_ID"],
      key_filepath: ENV["APPLE_STORE_CONNECT_KEY_FILEPATH"],
    )

    upload_to_testflight(
      changelog: "Thank you for testing pre-release builds of LunaSea! Please consider joining the Discord to give feedback to the developer.\n\nChanges can be found on GitHub or by going to settings/system and tapping on the version tile!",
      distribute_external: true,
      groups: options[:groups] || "internal",
      pkg: options[:pkg] || "../macos/LunaSea.pkg",
      notify_external_testers: true,
    )
  end
end
