# Passa a Free le società con disdetta programmata e periodo scaduto (anche senza visita pagina billing).
class ExpireEndedSubscriptionsJob
  include Sidekiq::Job

  def perform
    free_plan = Plan["free"]

    Subscription.where(cancel_at_period_end: true)
                  .where("current_period_end <= ?", Time.current)
                  .where.not(plan_id: free_plan.id)
                  .find_each do |sub|
      Billing::Stripe::FinalizeSubscription.call(club: sub.club)
    rescue StandardError => e
      Rails.logger.warn("[ExpireEndedSubscriptions] club=#{sub.club_id} #{e.message}")
    end
  end
end
