class PanMessage < Base::PanMessage
  attr_accessor :recipients

  associations_for legacy: true do |a|
    a.belongs_to :school
    a.belongs_to :user, foreign_key: :FromUID
  end

  has_many :pan_recipients, foreign_key: :MessageID, inverse_of: :pan_message, dependent: :destroy

  after_initialize :create_recipient_associations, if: :new_record?

  before_save :set_unique_id, if: :new_record?
  after_save :delete_all_pans, if: :deleted?

  validates :subject, presence: true
  validates :body, presence: true
  validates :date, presence: true

  scope :ordered, -> { order(date: :desc) }

  def self.to_or_from(user_id)
    joins(:pan_recipients)
      .where('PANMessages.FromUID = :id OR PANRecipients.ToUID = :id', id: user_id)
  end

  private
    def set_unique_id
      self.unique_id = "pan#{SecureRandom.hex(6)}"
    end

    def create_recipient_associations
      to_users = recipients.presence || [nil]

      to_users.each do |recipient|
        pan_recipients.build(
          school: school,
          subject: subject,
          date: date,
          author: user,
          recipient: school.users.find_by(id: recipient)
        )
      end
    end

    def delete_all_pans
      return unless pan_recipients.all?(&:deleted?)

      destroy
    end
end
