class ManagementsValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    return unless record.eventable.is_a?(Expedient)
    return if Expedient::WITHOUT_MANAGEMENTS.include?(record.classification_type)
    exp = record.eventable
    if exp.managements.count == 0
      record.errors[attribute] << (options[:message] || "No tiene gestiones, por favor agregue al menos una")
    end
    if exp.managements.pluck(:state).include?('process')
      record.errors[attribute] << (options[:message] || "Para poder cerrar el caso, por favor cierre todas sus gestiones")
    end
  end
end

class Event < ApplicationRecord
  belongs_to :eventable, polymorphic: true, touch: true
  belongs_to :user, optional: true

  delegate :new?, :closed?, :process?, to: :current_state

  validates :state, presence: true
  validates :justification, managements: true, if: Proc.new{ |obj| obj.state == 'closed'}
  validates :weight, presence: true, if: Proc.new{ |a| a.eventable_type == 'Management' && a.state == 'closed' }
  validates :response, :classification_type, presence: true, if: Proc.new{ |a| a.eventable_type == 'Expedient' && a.state == 'closed' }
  validates :resolution_type, presence: true, if: Proc.new{ |a| a.state == 'closed' && a.eventable.is_a?(Expedient) && a.eventable.needs_resolution_type? }
  validates :it_proceeds, presence: true, if: Proc.new{ |a| a.state == 'closed' && a.eventable.is_a?(Expedient) && a.eventable.it_proceeds? }

  before_create :update_status_expedient, if: Proc.new{ |obj| obj.eventable.is_a?(Expedient) }

  scope :failed_attempts, -> {where(state: 'failed_communication_attempt').order(:created_at)}

  attr_accessor :weight, :kind, :management_category_id, :failed_attempt
  attr_accessor :classification_type, :resolution_type, :it_proceeds, :response

  private
    def update_status_expedient
      unless state=='failed_communication_attempt'
        eventable.update_column(:state, self.state)
        # Set correlative and reference code to expedient
        eventable.set_correlative_and_code if process?
        # Set closed info
        eventable.update_columns(
          classification_type: self.classification_type,
          resolution_type: self.resolution_type,
          it_proceeds: self.it_proceeds,
          response: self.response
        ) if closed?
      end
    end

    def current_state
      state.inquiry
    end
end
