class Service::FamilyLog < ApplicationRecord
  include Base::Service::FamilyLog

  audited

  enum status: { pending: 0, approved: 1, denied: 2 }

  attr_accessor :skip_actioncable

  belongs_to :family, inverse_of: :service_logs, foreign_key: :FamilyID
  belongs_to :author, class_name: :User, foreign_key: :AuthorID, inverse_of: :service_family_logs
  belongs_to :opportunity, foreign_key: :SOID, inverse_of: :family_logs
  belongs_to :school_year, inverse_of: :service_family_logs

  delegate :school, to: :family

  before_validation :set_school_year, unless: :school_year_id?
  before_update :send_notifications, if: -> { approved? && status_was != 'approved' }
  after_create :send_notifications, if: :pending?

  validates :datetime, presence: true
  validates :hours, numericality: { greater_than_or_equal_to: 0 }

  scope :by_date_range, ->(range) { where(datetime: range) if range.present? }
  scope :by_school_year, ->(year) { where(school_year: year) if year.present? }
  scope :by_status, ->(status) { where(status: status) if status.present? }
  scope :by_family_ids, ->(ids) { where(family_id: ids) if ids.present? }
  scope :by_opportunity_ids, ->(ids) { where(opportunity_id: ids) if ids.present? }

  def created_at_or_created_dt
    created_at || self.CreatedDT
  end

  private
    def set_school_year
      self.school_year = school.current_year if school_year.blank?
    end

    def send_notifications
      Notification::Service::FamilyLogJob.perform_async(id, status)
    end
end
