# 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

require 'dotenv'

package_json_content = File.read('../package.json')
package_json = JSON.parse(package_json_content)
version = package_json['version']

default_platform(:ios)

owner_name = "STS-ReactNative" # Update this value if you are not work on Saigon Technology Solutions

teamId = ENV["APPLE_TEAM_ID"]
envs = ['development', 'staging', 'production']
env = ''

platform :ios do
  before_all do |lane, options|
    env = assert_environment(**options)
  end

  desc "Build and upload to TestFlight or Firebase App Distribution"
  lane :upload do |options|
    appName = ENV["APP_NAME"]
    
    # Validate required environment variables
    UI.user_error!("APP_NAME environment variable is required") if appName.nil? || appName.empty?
    UI.user_error!("PROJECT_NAME environment variable is required") if appName.nil? || appName.empty?

    appName = appName.gsub(" ", "")
    workspace ="./ios/#{appName}.xcworkspace"
    xcodeproj = "./ios/#{appName}.xcodeproj"

    envName = case env
    when "development"
      "Development"
    when "staging"
      "Staging"
    when "production"
      "Production"
    else
      "Development"
    end

    increment_version_number(xcodeproj: xcodeproj, version_number: version)

    if options[:ci]
      increment_build_number(xcodeproj: xcodeproj, build_number: options[:buildNumber])
      cert
      sigh(
        force: true,
        app_identifier: ENV["APP_ID"],
        team_id: teamId,
      )

      update_code_signing_settings(
        use_automatic_signing: false,
        team_id: teamId,
        bundle_identifier: ENV["APP_ID"],
        profile_name: ENV["APP_ID"] + " AppStore",
        targets: [appName],
        code_sign_identity: 'Apple Distribution',
        path: xcodeproj
      )

      unlock_keychain(
        password: ENV["KEYCHAIN_PASSWORD"]
      )
    end

    build_app(
      workspace: workspace,
      scheme: appName,
      clean: true,
      xcargs: "-allowProvisioningUpdates",
      export_method: "app-store",
      export_options: {
        uploadBitcode: false,
        compileBitcode: false,
        provisioningProfiles: {
          ENV["APP_ID"] => ENV["APP_ID"] + " AppStore"
        }
      }
    )

    upload_to_testflight(
      skip_waiting_for_build_processing: true,
      app_identifier: ENV["APP_ID"],
        changelog: "#{envName} - #{Time.now.strftime('%d %b %Y')}",
      itc_provider: teamId
    )
  end

  desc "Build iOS app"
  lane :build do |options|
    upload(env: options[:env], buildNumber: options[:buildNumber], ci: options[:ci], changelog: options[:changelog])
  end
end



platform :android do
  before_all do |lane, options|
    env = assert_environment(**options)
  end

  desc "Build file apk and upload to firebase app distribution"

  lane :upload do |options|
    envName = case env
    when "development"
      "Development"
    when "staging"
      "Staging"
    when "production"
      "Production"
    else
      "Development"
    end

    if env === 'production'
      build_type = "AAB"
      task = "bundle"
    else
      build_type = "APK"
      task = "assemble"
    end

    gradle(
      task: task,
      build_type: "Release",
      project_dir: "./android",
      # properties: {
      #   "VERSION_NAME" => version,
      #   "versionCode" => options[:buildNumber] || "1"
      # }
    )

    # Determine output path based on build type
    if env === 'production'
      output_path = lane_context[SharedValues::GRADLE_AAB_OUTPUT_PATH]

      UI.message("Production environment - uploading to Google Play Console")

      # Upload to Google Play Console
      upload_to_play_store(
        package_name: ENV["APP_ID"],
        version_name: version,
        version_code: options[:buildNumber] || "1",
        json_key: ENV["GOOGLE_PLAY_JSON_KEY_PATH"],
        aab: output_path,
        skip_upload_apk: true,
        skip_upload_metadata: true,
        skip_upload_changelogs: true,
        skip_upload_images: true,
        skip_upload_screenshots: true
      )

      UI.success("AAB built successfully for production!")
    else
      # Find the correct APK path for the environment
      output_path = lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH]

      UI.message("Using APK path: #{output_path}")

      # Upload to Firebase App Distribution for development/staging
      UI.message("Uploading to Firebase App Distribution...")

      firebase_app_distribution(
        app: ENV["FIREBASE_APP_ID"],
        release_notes: "#{envName} - #{Time.now.strftime('%d %b %Y')}",
        groups: ENV["DISTRIBUTE_GROUP"],
        android_artifact_type: build_type,
        android_artifact_path: output_path,
        firebase_cli_token: ENV["FIREBASE_TOKEN"],
      )
    end
  end

  desc "Build Android app"
  lane :build do |options|
    upload(env: options[:env], buildNumber: options[:buildNumber], changelog: options[:changelog])
  end
end

private_lane :assert_environment do |options|
  env = if options[:env] != nil
    options[:env].downcase
  elsif ENV.key?('APP_ENV')
    ENV['APP_ENV']
  else
    UI.user_error!('Whoops, missing environment: Use `fastlane --env VALUE` where VALUE can be: ' + envs.inspect)
    prompt_for_environment
  end
end
