class Communication::BatchEmail < ApplicationRecord
  enum status: { draft: 0, scheduled: 1, queued: 2, processing: 3, sent: 4, failed: 5 }
  enum editor_type: { text: 0, design: 1 }

  belongs_to :school
  belongs_to :author, class_name: '::User', primary_key: :UserID

  has_many :recipients, class_name: 'Communication::BatchEmailRecipient',
    foreign_key: :batch_email_id, dependent: :destroy, autosave: true, inverse_of: :batch_email
  has_many :employees, through: :recipients, source: :associated, source_type: 'Employee'
  has_many :contacts, through: :recipients, source: :associated, source_type: 'Contact'
  has_many :students, through: :recipients, source: :associated, source_type: 'Student'

  scope :by_status, ->(status) { where(status: status) }

  def send_email
    return if processing? || sent?

    queued!
    Sparkpost::TransmissionJob.perform_async(id)
  end
end
