# 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

default_platform(:android)

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

  desc "CRITICAL: Runs comprehensive data integrity tests - NO DATA LOSS ALLOWED!"
  lane :data_integrity_tests do
    puts "🛡️  STARTING CRITICAL DATA INTEGRITY TESTS"
    puts "⚠️  MISSION: ENSURE ZERO DATA LOSS!"
    puts "=================================================================="
    
    # Clean build first
    gradle(task: "clean")
    
    # Build debug version
    gradle(task: "assembleDebug")
    
    begin
      # Run core data integrity tests
      puts "🔍 Testing core file integrity..."
      gradle(
        task: "test", 
        flags: "--tests de.schliweb.sambalite.data.repository.SmbRepositoryDataIntegrityTest --info"
      )
      
      # Run performance stress tests
      puts "⚡ Testing under performance stress..."
      gradle(
        task: "test",
        flags: "--tests de.schliweb.sambalite.test.performance.SmbRepositoryPerformanceIntegrityTest --info"
      )
      
      # Run Android instrumented tests if possible
      begin
        puts "📱 Testing Android-specific integrity..."
        gradle(
          task: "connectedAndroidTest",
          flags: "--tests de.schliweb.sambalite.data.repository.SmbRepositoryAndroidDataIntegrityTest"
        )
      rescue => android_error
        puts "⚠️  Android tests skipped (no device connected): #{android_error}"
      end
      
      puts "=================================================================="
      puts "🎉 SUCCESS: ALL DATA INTEGRITY TESTS PASSED!"
      puts "✅ NO DATA LOSS DETECTED!"
      puts "✅ File operations are SAFE and RELIABLE!"
      puts "=================================================================="
      
    rescue => e
      puts "=================================================================="
      puts "❌ CRITICAL FAILURE: DATA INTEGRITY COMPROMISED!"
      puts "🚨 ERROR: #{e.message}"
      puts "🚨 IMMEDIATE ACTION REQUIRED!"
      puts "🚨 DO NOT RELEASE UNTIL ALL TESTS PASS!"
      puts "=================================================================="
      raise e
    end
  end

  desc "Clean"
  lane :clean do
    gradle(task: "clean")
  end

  desc "Deploy a new version to the Google Play"
  lane :deploy do
    upload_to_play_store(
      track: "internal", # oder "alpha", "beta", "production"
      aab: File.join(__dir__, "./app/release/app-release.aab")
    )

  end

  desc "Builds a signed Android App Bundle (.aab) and APK for release"
  lane :build_signed_bundle_apk do
    gradle(
      task: "bundle",
      build_type: "Release",
      properties: {
        "android.injected.signing.store.file" => ENV["KEYSTORE_PATH"],
        "android.injected.signing.store.password" => ENV["KEYSTORE_PASSWORD"],
        "android.injected.signing.key.alias" => ENV["KEYSTORE_ALIAS"],
        "android.injected.signing.key.password" => ENV["KEY_PASSWORD"]
      }
    )

    aab_path = File.join(__dir__, "../app/build/outputs/bundle/release/app-release.aab")
    destination_folder = File.join(__dir__, "../app/release")
    FileUtils.mkdir_p(destination_folder)
    FileUtils.cp(aab_path, destination_folder)
    UI.success("Copied .aab file to #{destination_folder}")

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

    apk_path = File.join(__dir__, "../app/build/outputs/apk/release/app-release.apk")
    destination_folder = File.join(__dir__, "../app/release")
    FileUtils.mkdir_p(destination_folder)
    FileUtils.cp(apk_path, destination_folder)
    UI.success("Copied signed APK to #{destination_folder}")

    increment_version_code(gradle_file_path: "./app/build.gradle")
  end

  desc "Tags the Android release and pushes the tag to the origin"
  lane :tag_and_push_bundle do
    aab_path = File.join(__dir__, "../app/release/app-release.aab")

    if !File.exist?(aab_path)
      UI.error("The .aab file does not exist at: #{aab_path}")
      exit 1
    end

    apk_path = File.join(__dir__, "../app/release/app-release.apk")

    if !File.exist?(aab_path)
      UI.error("The .apk file does not exist at: #{apk_path}")
      exit 1
    end

    version_file = File.join(__dir__, "../build.gradle")
    version = nil
    File.foreach(version_file) do |line|
      if line.match(/version\s*=\s*['"](.*)['"]/)
        version = line.match(/version\s*=\s*['"](.*)['"]/)[1]
        break
      end
    end
    if version.nil?
      UI.error("Could not find a version in #{version_file}")
      exit 1
    end

    tag_name = "v#{version}"

    add_git_tag(
      tag: tag_name,
      message: "Release for bundle: #{tag_name}"
    )

    push_git_tags

    set_github_release(
      repository_name: "egdels/SambaLite",
      api_token: ENV["GITHUB_API_TOKEN"],
      tag_name: tag_name,
      upload_assets: ["./app/release/app-release.aab","./app/release/app-release.apk"]
    )
  end
end
