class Promotion < ActiveRecord::Base
  ##--- Llevar registro de Actividad del usuario
  audited

  belongs_to :product
  belongs_to :category
  # belongs_to :subcategory_id, class_name: "Category"

  enum status: [:inactive, :active]

  validates_presence_of :start_date, message: "Debe indicar fecha de inicio de la promoción."
  validates_presence_of :end_date, message: "Debe indicar fecha de término de la promoción."
  validates_presence_of :percent, message: "Debe indicar el porcentaje de descuento de la promoción."
  validates :percent, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 100 }
  validate :start_end_date, on: [:create]

  validate :start_date_greater_than_end_date, if: proc { |p| p.start_date.present? && p.end_date.present? }
  validate :promotion_source
  validate :check_for_duplicates

  scope :activas, -> { where(status: 1) }
  scope :vigentes, -> { where("? between start_date and end_date", Date.today) }

  def verify_promotion
    is_active = end_date >= Date.today
    unless is_active
      update_attribute(:status, :inactive)
    end
  end

  def start_end_date
    if end_date.present? && end_date < Date.today
      errors.add(:end_date, "La fecha de fin debe ser mayor a hoy.")
    end
  end

  def start_date_greater_than_end_date
    if end_date < start_date
      errors.add(:start_date, 'La fecha de inicio debe ser mayor a la fecha de término de la promoción.')
    end
  end

  def promotion_source
    if product_id.blank? && category_id.blank?
      errors.add(:base, 'Seleccione una opción entre línea o producto.')
    end
  end

  def check_for_duplicates
    source =
      if category_id.present?
        "category_id = #{category_id}"
      elsif subcategory_id.present? && subcategory_id != "0"
        "subcategory_id = #{subcategory_id}"
      elsif product_id.present?
        "product_id = #{product_id}"
      end
    if source
      exists_already = Promotion.activas.where(source).where("start_date < ? AND end_date > ?", end_date, start_date).any?
      errors.add(:base, 'Ya existe una promoción activa con los parámetros seleccionados') if exists_already
    end
  end
end
