module Contract::States
  extend ActiveSupport::Concern

  included do
    include AfterCommitQueue

    state_machine :initial => :pending do
      state :pending

      state :live
      state :suspended
      state :deprecated

      after_transition :to => :suspended, :do => :suspend_after_commit
      after_transition :to => :live, :do => :accept_after_commit
      # there is no schedule_for_destroy
      # after_transition :to => :deprecated, :do => :schedule_for_destroy

      event :accept do
        transition :pending => :live
      end

      event :suspend do
        transition :live => :suspended
      end

      event :resume do
        transition :suspended => :live
      end

      event :deprecate do
        transition :live => :deprecated
      end
    end
  end

  module ClassMethods
    def allowed_states
      state_machine.states.keys - [:deprecated]
    end

    def by_state(state)
      if state.present?
        where(state: state.to_s)
      else
        where({})
      end
    end
  end

  def suspend_after_commit
    if self.is_a?(Cinstance)
      @webhook_event = 'suspended'
    end
    run_after_commit(:suspend_callbacks)
  end

  def accept_after_commit
    run_after_commit do
      notify_observers(:accepted)
    end
  end

  def suspend_callbacks
    messenger.suspended(self).deliver
  end
end
