namespace :lndhub do
  desc "Generate wallets for all users"
  task :generate_wallets => :environment do |t, args|
    User.all.each do |user|
      CreateLndhubWalletJob.perform_later(user)
    end
  end

  desc "List wallet balances"
  task :balances => :environment do |t, args|
    sum = 0
    User.all.each do |user|
      lndhub = Lndhub.new
      auth_token = lndhub.authenticate(user)
      data = lndhub.balance(auth_token)
      balance = data["BTC"]["AvailableBalance"] rescue nil
      if balance && balance > 0
        sum += balance
        puts "#{user.address}: #{balance} sats"
      end
    end
    puts "--\nSum of user balances: #{sum} sats"
  end

  desc "Migrate existing accounts to lndhub.go"
  task :migrate => :environment do |t, args|
    # user = User.find_by cn: "jimmy"
    User.all.each do |user|
      puts "Migrating #{user.cn}"
      puts "Creating account..."
      lndhub_v2 = LndhubV2.new
      res = lndhub_v2.create_account login: user.ln_login, password: user.ln_password
      puts res.inspect

      lndhub = Lndhub.new
      lndhub.authenticate(user)
      data = lndhub.balance
      balance = data["BTC"]["AvailableBalance"] rescue 0

      if balance > 0
        lndhub_v2.authenticate(user)
        desc = "Balance migration from old Kosmos Lightning back-end"
        res = lndhub_v2.create_invoice amount: balance, description: desc
        puts "Payment request for #{user.cn} (#{balance} sats):"
        puts res["payment_request"]
      end

      puts "---"
    end
  end
end
