class Broadcast < ApplicationRecord
  include PgSearch

  belongs_to :project
  has_many :broadcast_recordings, dependent: :destroy
  has_many_attached :files

  has_secure_token

  validates :name, presence: true

  enum status: [:created, :active, :idle]
  enum streamer_status: [:idle, :connected, :recording, :disconnected], _prefix: "streamer"

  # Should we use callbacks for this, or something else?
  after_create :create_mux_live_stream
  after_destroy :destroy_mux_live_stream

  pg_search_scope :search, {
    against: [:name],
    using: {
      tsearch: { any_word: true, prefix: true },
      trigram: {},
      dmetaphone: { any_word: true }
    }
  }

  def stream_playback_url
    # TODO: This may change when we start using signed playback policy
    "https://stream.mux.com/#{stream_playback_uid}.m3u8"
  end

  def stream_server_url
    ENV['MUX_BROADCAST_SERVER_URL']
  end

  def zoom_meeting_url
    project.zoom_meeting_url
  end

  private

  def create_mux_live_stream
    stream = MuxLiveStream.new

    self.stream_uid = stream.id
    self.stream_key = stream.key
    self.stream_playback_uid = stream.playback_id
    self.save!
  end

  def destroy_mux_live_stream
    begin
      stream = MuxLiveStream.new
      stream.destroy_stream(self.stream_uid)
    rescue MuxRuby::NotFoundError
    rescue MuxRuby::ApiError => e
      Rails.logger.error("Failed to delete live stream id #{stream_uid}\n" + e.message)
      raise ActiveRecord::Rollback
    end
  end
end
