module Sessions
  class Stop
    def initialize(session)
      @session = session
    end

    def call
      cancel_timeout_job
      Sessions::RegiaAccess.revoke!(@session)
      @session.end_stream!
      Youtube::BroadcastService.new(@session.match.team).complete_broadcast!(@session.youtube_broadcast_id)
      Recordings::IndexSession.new(@session).call
      Mediamtx::Client.new.delete_path(@session)
      log_event("ended")
      SessionChannel.broadcast_message(@session, { type: "stream_event", event: "ended" })
      @session
    end

    private

    def cancel_timeout_job
      return if @session.timeout_job_id.blank?

      Sidekiq::ScheduledSet.new.find_job(@session.timeout_job_id)&.delete
    end

    def log_event(type)
      @session.stream_events.create!(event_type: type, occurred_at: Time.current, metadata: {})
    end
  end
end
