namespace :auto_recharge_sim do
  desc "Auto Recharge for sim management"
  task sim_auto_recharge: :environment do
    sim_managements = SimManagement.all
      sim_managements.each do |sim|
        if sim.auto_recharge == true && sim.is_active == "true"
          if sim.purchase_orders.present? 
            if sim.purchase_orders.last.payment_invoices.pluck(:payment_status).first == "success"
              amount = sim.purchase_orders.last.sim_rate_plan.amount
              invoice_date = sim.purchase_orders.last.payment_invoices.pluck(:invoiced_on).first
              next_charge_date = invoice_date + 1.month
              customer_id = sim.purchase_orders.last.payment_invoices.pluck(:customer_id).first
              puts customer_id.inspect
              if next_charge_date.to_date == Date.today
                #retrive_customer = Stripe::Customer.retrieve(customer_id)
                puts "coming to charge_customer"
                charge_customer = Stripe::Charge.create(
                      :amount => amount.to_i*100, # in cents
                      :currency => "usd",
                      :customer => customer_id,
                      :description => "Charge for recurring SimPayment"
                  )
                puts charge_customer.inspect
                puts "striped worked"
                if charge_customer["status"] == "succeeded"
                  invoice_number = "PN-" + SecureRandom.hex(3)
                  puts "charged successfulley"
                else
                  puts "Not able to charge due to some problem"  
                end 
              end    
            end
          end     
        end
      end
  end
end

